<?php
namespace Admin\Frontend\Controllers;

use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\res\XhresReferenceApply;
use Admin\Models\res\XhresReferenceNote;
use Admin\Models\res\XhresReferenceRepeal;
use Admin\Models\res\XhresReferencePlan;
use Admin\Models\res\XhresReferenceSchedule;
use Admin\Models\res\XhresReferenceCheck;
use Admin\Models\sys\XhsysUserTch;
use Helpers\Area;
use Helpers\HttpClient;
use Helpers\Tool;
use Helpers\Main;
use Helpers\User;
use Helpers\UserPower;
use Helpers\Template;
use Helpers\Assets;
use Helpers\Hrm;
use Admin\Models\log\XhlogCommit;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\res\XhresQuestionbank;
use Admin\Models\res\XhresQuestionbankcontact;
use Admin\Models\res\XhresResourcepack;
use Admin\Models\res\XhresResourcepackcontact;
use Admin\Models\res\XhresResourcepackusers;
use Admin\Models\user\XhsysUser;
use Modules\Power;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Admin\Models\res\Books;
use Admin\Models\res\SchoolBase;
use Admin\Models\res\QuestionPrivilege;
use Admin\Models\res\Dictionaries;
use Services\App;
use Services\ResPrivilege;
use Services\ResAreaGroup;
use Services\CloudTask;
use Endroid\QrCode\QrCode;

class ResController extends ControllerBase
{
    private $registerEnum = [
        'referenceApply'  => [
            'iStatus'      => ['0' => '待审核', '1' => '待定', '2' => '完成', '3' => '拒绝', '4' => '资料准备中', '5' => '已上架'],
            'bExistBookId' => ['0' => '否', '1' => '是'],
            'bPaperBook'   => ['0' => '否', '1' => '是'],
            'bElectronic'  => ['0' => '否', '1' => '是'],
            'iPublishStatus' => [0 => '未录入', 1 => '录入中', 2 => '待校对', 3 => '校对中', 4 => '已校对', 5 => '已发布'],//6 => '已拒绝'去掉
            'iExistPlan' => [0 => '无', 2 => '新申请', 3 => '已过期', 1 => '有'],
            'iDemandStatus' => [0 => '未完成', 1 => '完成'],
            'iBookStatus' => [1 => '未完成', 2 => '未完成', 3 => '完成', 4 => '未完成'],
            'iRefuseHandle' => [1 => '处理中', 2=> '待沟通', 3 => '已处理'],
            'iCompleteStatus' => [1 => '已完成', 2 => '未完成']
        ],
        'referenceRepeal' => [
            'iStatus' => ['0' => '待审核', '1' => '通过', '2' => '未通过']
        ],
        'userType'        => [1 => '学生', 2 => '教师', 3 => '家长', 4 => '通用'],
        'resStatus'       => [0 => '录入中', 1 => '录入中', 2 => '待校对', 3 => '校对中', 4 => '待发布', 5 => '已完成'],
    ];
    private $areaGroupEnum = [
        'iStage'   => [1 => '小学', 2 => '初中', 3 => '高中'],
        'areaType' => [1 => '省', 2 => '市', 3 => '区'],
    ];
    private $schoolSort = ['1', '10', '3563', '3614', '3618', '4160'];
    private $existPlanStatus = [1 => '已申请', 2 => '未申请'];
    private $referenceApply = [0 => '不允许', 1 => '允许'];
    private $scheduleSummary = [0 => '未操作', 1 => '同意(默认)', 2 => '同意', 3 => '不同意', 4 => '已取消', ];
    private $dealStatus = [0 => '未处理', 1 => '已处理'];
    private $appPageToAppCode = ['com.xh.acldtch' => 'CA103001', 'com.xh.abrutch' => 'CA101010'];//包名转code
    private $checkTypeStatus = [1 => '同意', 2 => '不同意'];
    public function getBookSubjectEnum($key)
    {
        $allEnum = $this->getEnumTypeList();
        return isset($allEnum[$key]) ? $allEnum[$key] : [];
    }

    /**
     * 资源库书libraryType枚举
     *
     * @return array
     *
     * create by qgz 20180829
     */
    public function runLibraryType()
    {
        return array(
            1  => '同步教辅书',
            2  => '校本题库',
            3  => '个人题库',
            5  => '自加题库',
            8  => '专题教辅书',
            9  => '引用教辅书',
            10 => '校本自建书',
            11 => '个人自建书',
        );
    }

    /**
     * 题库列表页面
     *
     * create by ck 20160307
     * modify by ck 20160616    优化
     * modify by ck 20160902    结构更改
     * modify by ck 20160923    js压缩
     */
    public function questionBankListAction()
    {
        $this->view->pick('res/questionBankList');
        Assets::easyUI('js/res/questionBankList.js');
        Main::showNavPosition();
        UserPower::checkUserPower('Res_QBank_List') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109103001));
        Template::exists('XHRes_QuestionBank', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109103002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (UserPower::checkUserPower('Res_QBank_List_Add')) {
            $listButtonArr[] = array('id' => 'bt_list_add', 'text' => '增加', 'plain' => 'true', 'icon' => 'fa-plus');
            $formButtonArr[] = array('id' => 'bt_form_add', 'text' => '增加', 'class' => 'disabled');
            $this->view->setVar('AddEdit', true);
        }
        if (UserPower::checkUserPower('Res_QBank_List_Edit')) {
            $formButtonArr[] = array('id' => 'bt_form_edit', 'text' => '修改', 'class' => 'disabled');
            $this->view->setVar('AddEdit', true);
        }
        if (UserPower::checkUserPower('Res_QBank_List_Del')) {
            $listButtonArr[] = array('id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash');
        }
        if (UserPower::checkUserPower('Res_QBank_List_Pack')) {
            $listButtonArr[] = ['id' => 'bt_list_Pack', 'text' => '打包', 'plain' => 'true', 'icon' => 'fa-inbox'];
            $listButtonArr[] = ['id' => 'bt_list_PackOnly', 'text' => '打包不上传', 'plain' => 'true', 'icon' => 'fa-inbox'];
            $listButtonArr[] = ['id' => 'bt_list_Dict', 'text' => '生成字典', 'plain' => 'true', 'icon' => 'fa-language'];
//            $listButtonArr[] = array('id'=>'bt_list_PackUpdate', 'text'=>'更新打包', 'plain'=>'true', 'icon'=>'fa-inbox');
            if (isset(Main::getConfigByName('cBookShelf')['synUrl'])) {
                $listButtonArr[] = ['id' => 'bt_list_syn', 'text' => '同步', 'plain' => 'true', 'icon' => 'fa-share'];
            }
            $listButtonArr[] = ['id' => 'bt_list_push', 'text' => '推送', 'plain' => 'true', 'icon' => 'fa-send'];
        }
        $listButtonArr[] = ['id' => 'bt_list_Download', 'text' => '下载', 'plain' => 'true', 'icon' => 'fa-download'];
        $formButtonArr[] = array('id' => 'bt_form_back', 'text' => '返回');
        $formButtonArr[] = array('id' => 'bt_form_reset', 'text' => '重置');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'name' => 'list_search', 'label' => '搜索： ');
//        $listSearchArr[] = array('type'=>'select', 'id'=>'List_Search_Choose', 'data'=>['书名'=>'sBookName','题库ID'=>'iQBankId'], 'multiple'=>'true');
        $this->view->setVars(array(
            'List' => Template::createList('List', 'XHRes_QuestionBank', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'Form' => Template::createForm('XHRes_QuestionBank'),
            'FormButton' => Template::createButtonToolBar($formButtonArr)
        ));
    }

    /**
     * 根据页码及每页行数获取数据并以json格式返回
     *
     * create by ck 20160307
     * modify by ck 20160923    使用公共方法
     */
    public function getQBankListAction()
    {
        $this->view->disable();
        $appCode = $this->request->getPost('iAppCode', 'string');      //应用编号
        $schoolId = $this->request->getPost('iSchoolId', 'int');     //学校ID
        $dataType = $this->request->getPost('type', 'string');       //是否绑定
        $schoolId = $schoolId ? $schoolId : 0;
        $contactSql = "SELECT B.iQBankId FROM \\Admin\\Models\\res\\XhresQuestionbankcontact AS B WHERE B.bDelete=0 AND B.iAppCode='{$appCode}' AND (B.iSchoolId = 0 OR B.iSchoolId={$schoolId})";
        $parameters = array();                                         //查询条件数组
        if ($dataType == 'in') $parameters['conditions'] = "bDelete = 0 AND iQBankId IN ({$contactSql})";
        elseif ($dataType == 'out') $parameters['conditions'] = "bDelete = 0 AND iQBankId NOT IN ({$contactSql})";
        else $parameters['conditions'] = 'bDelete = 0';
        Main::runSearchVagueConditions($parameters['conditions'], array('sBookName', 'iQBankId', 'sCourseName', 'sGradeName', 'sSortName'));
        $parameters['columns'] = 'iQBankId,sQBVersion,sBookName,sQBDownUrl,sQBMd5,sGradeName,sCourseName,sSortName,bAudio,bDict,tPackDate,iQBookSize';
        $result = Main::runModelPaginator('\\Admin\\Models\\res\\XhresQuestionbank', $parameters, true);
        Tool::runByteToMByte($result['rows'], 'iQBookSize');
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 根据题库ID组成下载url并返回
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170409
     */
    public function getQBankDownUrlAction()
    {
        $this->view->disable();
        $id = $this->request->getPost('id', 'int');
        $id or die;
        $url = Main::getConfigByName('resDown');
        $url = $url['qBank'];
        $url or $url = 'http://down3.yunzuoye.net/BookPack/XHBookFiles/';
        $url .= "book_exam{$id}.100fen2";
        return $this->response->setContent($url);
    }

    /**
     * 插入，修改数据，如id已存在，则修改，否则新增
     *
     * create by ck 20160307
     * modify by ck 20160811    去掉mongo
     * modify by ck 20160909    修改信息后刷新关联的应用题库
     * modify by ck 20161102    添加图片上传
     * modify by ck 20161216    图片保存路径改为配置文件
     * modify by ck 20170122    优化文件上传，添加判断防止报错
     */
    public function modifyQBankDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $realData = Main::getRealData($this->request->getPost());
        $new = true;
        $questionBank = XhresQuestionbank::createRecord($realData, $new);
        UserPower::checkUserPower($new ? 'Res_QBank_List_Add' : 'Res_QBank_List_Edit')
        or die(Main::showMessageModal('无操作权限!', 109103003));
        while ($this->request->hasFiles()) {
            $files = $this->request->getUploadedFiles();
            if (!$files[0]->getName()) break;
            //add by ck 20161216 start
            $filePath = Main::getConfigByName('appParse');
            $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
            //add by ck 20161216 end
            foreach ($files as $file) {
                if (!$file->getName()) continue;
                if (!$file->getRealType()) break;
                $fileType = explode('/', $file->getRealType());
                $fileType = $fileType[0];
                if ($fileType != 'image') die(Main::showMessageModal(109103015, '文件格式错误！'));
                //mark by ck 20161216
//                $filePath = 'files/temp';
//                if (!is_dir($filePath)) mkdir($filePath, 0777, true);
                $fileName = $file->getName();
                $fullPath = $filePath . $fileName;
                if (!is_writable($filePath)) die(Main::showMessageModal(109103016, '无写入权限！'));
                $file->moveTo($fullPath);
                $url = Main::uploadToFileManageSystem($fullPath, 'qBankCover', 'XHSVADTKBSCECK');
                @unlink($fullPath);
                if ($url) $questionBank->sCoverUrl = $url;
            }
            break;
        }
        $result = $new ? $questionBank->insertData() : $questionBank->updateData();
        $result or die(Main::showMessageModal('执行失败！', 109103004));
        echo '执行成功！';
        Main::createCommitLog('res', 'QuestionBank', $new ? 'add' : 'edit', $questionBank);
        XhresQuestionbankcontact::refreshBookshelfByQuestionBankId($questionBank->iQBankId);
    }

    /**
     * 根据传入id字符串，根据逗号分割后删除记录
     *
     * create by ck 20160307
     * modify by ck 20160923
     */
    public function delQBankAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        UserPower::checkUserPower('Res_QBank_List_Del') or die('（109103005）无删除权限！');
        $ids = $this->request->getPost('ids');
        XhresQuestionbank::deleteRecordById($ids) or die('（109103006）删除失败！');
        echo '删除成功！';
        Main::createCommitLog('res', 'QuestionBank', 'del', array('ids' => $ids), null, '批量删除');
    }

    /**
     * 题库与应用/学校关联和取消关联
     *
     * create by ck 20160308
     * modify by ck 20160616    优化
     * modify by ck 20160622    应用/学校关联题库
     * modify by ck 20160802    刷新书架协议更改
     * modify by ck 20160924    结构更改
     */
    public function contactAppQueBankAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $appCode = $this->request->getPost('iAppCode');
        $schoolId = $this->request->getPost('iSchoolId', 'int', 0);
        UserPower::checkUserPower($schoolId ? 'School_List_ContactQBank' : 'App_AppList_ContactQBank')
        or die(Main::showMessageModal('无操作权限！', 109103010));
        $dbRollback = false;                //事务标识
        $this->db->begin();                 //事务开始
        if ($this->request->getPost('type') == 'in') {
            $ids = explode(',', $this->request->getPost('iQBankIds'));
            foreach ($ids as $id) {
                $AppQuestion = XhresQuestionbankcontact::createRecord(array(
                    'iAppCode' => $appCode,
                    'iSchoolId' => $schoolId,
                    'iQBankId' => $id
                ));
                if (!$AppQuestion->insertData()) {
                    $dbRollback = true;
                    goto dealTrans;
                }
            }
            Main::createCommitLog('app', 'AppContactQBank', 'add',
                array('iAppCode' => $appCode, 'iSchoolId' => $schoolId, 'oQBankId' => $this->request->getPost('iQBankIds')),
                $schoolId, '应用-学校关联题库');
        } else {
            $ids = $this->request->getPost('iQBankIds');
            $contact = XhresQuestionbankcontact::getRecordByAppCodeSchoolQBankId($schoolId, $appCode, $ids);
            $contactExistId = array();
            foreach ($contact as $contactOne) {
                $contactExistId[] = $contactOne->iQBankId;
            }
            $ids = explode(',', $ids);
            $query = $contact->delete();
            if (!$query) {
                $dbRollback = true;
                goto dealTrans;
            }
            Main::createCommitLog('app', 'AppContactQBank', 'del',
                array('iAppCode' => $appCode, 'iSchoolId' => $schoolId, 'oQBankId' => $contactExistId),
                $schoolId, '应用-学校取消关联题库');
            if (count($ids) > count($contactExistId)) echo "<script>alert('（109103011）公用关联无法删除');</script>";
        }
        dealTrans:
        if ($dbRollback) {
            $this->db->rollback();
            die(Main::showMessageModal('操作失败！', 109103012));
        }
        $this->db->commit();
        echo '操作成功！';
        Main::refreshBookshelf($appCode, $schoolId);
    }

    /**
     * 异步调用后台打包程序
     *
     * create by ck 20160912
     * modify by ck 20160924    调用成功或失败返回信息
     * modify by ck 20161203    调用打包信息从配置信息读取
     * modify by ck 20170606    打包前检查需要字典文件的题库字典是否完整
     */
    public function packQuestionBankAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $ids = $this->request->getPost('ids', 'string');
        $ids or die(json_encode(['error' => 'id不能为空！']));

        //检查需要字典文件的题库字典文件是否完整
        $dictBank = XhresQuestionbank::find([
            'columns' => "iQBankId",
            'conditions' => "bDelete = 0 AND bDict = 1 AND iQBankId IN ({$ids})"
        ]);
        if ($dictBank) {
            $dictBankId = $dictBank->toArray();
            $dictBankId = array_column($dictBankId, 'iQBankId');
            try {
                $dbConfig = Main::getConfigByName('oldCenterDB');
                $db = new Mysql($dbConfig);
                foreach ($dictBankId as $id) {
                    $result = $db->fetchOne("select count(*) as count from xh_product_exam{$id}.homework_list_base where ho_child_flag = 0 and ho_zycontent <> '' and (ho_zypath = '' or ho_zypath2 = '')");
                    if ($result['count']) {
                        die(json_encode(['error' => "题库ID：{$id} 缺少字典文件！"]));
                    }
                }
            } catch (\Exception $e) {
                die(json_encode(['error' => '请联系管理员！错误：' . $e->getMessage()]));
            }
        }

        //add by ck 20161203 start
        $config = Main::getConfigByName('cPackQBank');
        $host = isset($config['ip']) ? $config['ip'] : 'localhost';
        $port = isset($config['port']) ? $config['port'] : '80';
        //add by ck 20161203 end
        $path = $this->url->getBaseUri() . 'Other/execPackQuestionBank';
        $query = http_build_query($this->request->getPost());
        $errNo = 0;
        $errStr = '';
        $timeout = 10;
        $fp = @fsockopen($host, $port, $errNo, $errStr, $timeout);
        if ($fp) {
            $out = "POST " . $path . " HTTP/1.1\r\n";
            $out .= "Host:" . $host . ":" . $port . "\r\n";
            $out .= "Content-Length:" . strlen($query) . "\r\n";
            $out .= "Content-Type:application/x-www-form-urlencoded\r\n";
            $out .= "Connection:close\r\n\r\n";
            $out .= $query;
            @fputs($fp, $out);
            @fclose($fp);
            return $this->response->setJsonContent(['time' => date('Y-m-d H:i:s')]);
        }
        return $this->response->setJsonContent(['error' => $errStr]);
    }

    /**
     * 同步题库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170728
     */
    public function synQuestionBankAction()
    {
        $ids = $this->request->getPost('ids');
        $ids = explode(',', $ids);
        $synUrl = Main::getConfigByName('cBookShelf')['synUrl'];
        $httpClient = new HttpClient($synUrl);
        $new = false;
        $errMsg = [];
        foreach ($ids as $id) {
            $response = $httpClient->get('/Help/getQBankInfo/' . $id);
            $body = $response->toArray();
            if ($body && !isset($body['error'])) {
                $bank = XhresQuestionbank::createRecord($body, $new);
                $result = $bank->save();
                XhresQuestionbankcontact::refreshBookshelfByQuestionBankId($id);
                if (!$result) {
                    $errMsg[] = $id . '保存失败';
                }
            } else {
                $errMsg[] = $id . '获取失败';
            }
        }
        if (!empty($errMsg)) {
            return $this->sendErrorResponse(200, '同步失败！', implode(' | ', $errMsg));
        }
        return $this->sendSuccessResponse('同步成功！');
    }

    /**
     * 检查打包是否完成（暂不支持打更新包）
     * 根据题库ID查询文件，题库ID以','隔开
     * 查询到的题库返回题库ID，查询不到则返回0
     *
     * create by ck 20160811
     * modify by ck 20160924    取消检查文件是否存在，查看信息是否更新
     * modify by ck 20161025    增加判断条件查看打包日期是否更新
     * modify by ck 20170122    检查时判断时间是否大于打包开始时间，失败则从日志获取信息返回
     */
    public function checkPackFileExistAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $questionBankIds = explode(',', $this->request->getPost('ids'));
        $packTime = $this->request->getPost('time', 'string');
        $existArr = array();
        foreach ($questionBankIds as $questionBankId) {
            $questionBank = XhresQuestionbank::findFirst('iQBankId = ' . $questionBankId);
            if (empty($questionBank->sPackInfo) || intval($questionBank->sPackInfo) != 0 || $questionBank->tPackDate <= $packTime) {
                $commitInfo = XhlogCommit::findFirst([
                    'columns' => 'sExplain',
                    'conditions' => "sOperate = 'packErr' AND iContentId = {$questionBankId} AND tCreateDate >= '{$packTime}'",
                    'order' => 'iCommitId desc',
                ]);
                if ($commitInfo) {
                    $existArr[] = ['iQBankId' => $questionBankId, 'tPackDate' => $commitInfo->sExplain];
                }
                continue;
            }
            $questionBank = $questionBank->toArray();
            $questionBank['bAudio'] = $questionBank['bAudio'] ? '是' : '否';
            $questionBank['bDict'] = $questionBank['bDict'] ? '是' : '否';
            $questionBank['iQBookSize'] = sprintf('%.2f', $questionBank['iQBookSize'] / (1024 * 1024)) . ' M';
            $existArr[] = $questionBank;
        }
        if (count($existArr) > 0) {
            echo json_encode($existArr);
            die;
        }
        die('0');
    }

    /**
     * 异步调用生成字典程序
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170606
     */
    public function dictQuestionBankAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $ids = $this->request->getPost('ids', 'string');
        $ids or die(json_encode(['error' => 'id不能为空！']));

        //检查所选题库是否需要生成字典
        $dictBank = XhresQuestionbank::findFirst([
            'columns' => "iQBankId",
            'conditions' => "bDelete = 0 AND bDict = 1 AND iQBankId IN ({$ids})"
        ]);
        $dictBank or die(json_encode(['error' => '所选题库不需要生成字典！']));

        //add by ck 20161203 start
        $config = Main::getConfigByName('cPackQBank');
        $host = isset($config['ip']) ? $config['ip'] : 'localhost';
        $port = isset($config['port']) ? $config['port'] : '80';
        //add by ck 20161203 end
        $path = $this->url->getBaseUri() . 'Other/execDictQuestionBank';
        $query = http_build_query($this->request->getPost());
        $errNo = 0;
        $errStr = '';
        $timeout = 10;
        $fp = @fsockopen($host, $port, $errNo, $errStr, $timeout);
        if ($fp) {
            $out = "POST " . $path . " HTTP/1.1\r\n";
            $out .= "Host:" . $host . ":" . $port . "\r\n";
            $out .= "Content-Length:" . strlen($query) . "\r\n";
            $out .= "Content-Type:application/x-www-form-urlencoded\r\n";
            $out .= "Connection:close\r\n\r\n";
            $out .= $query;
            @fputs($fp, $out);
            @fclose($fp);
            return $this->response->setJsonContent(['time' => date('Y-m-d H:i:s')]);
        }
        return $this->response->setJsonContent(['error' => $errStr]);
    }

    /**
     * 检查字典文件是否已生成
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170606
     */
    public function checkBookDictExistAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $ids = explode(',', $this->request->getPost('ids'));
        $dictTime = $this->request->getPost('time', 'string');
        $existArr = array();
        foreach ($ids as $id) {
            $commitInfo = XhlogCommit::findFirst([
                'columns' => 'sExplain',
                'conditions' => "sOperate in ('dictErr','dict') AND iContentId = {$id} AND tCreateDate >= '{$dictTime}'",
                'order' => 'iCommitId desc',
            ]);
            if ($commitInfo) {
                $existArr[] = ['iQBankId' => $id, 'bDict' => $commitInfo->sExplain];
                continue;
            }
        }
        if (count($existArr) > 0) {
            return $this->response->setJsonContent($existArr);
        }
        die('0');
    }

    /**
     * 资源包列表页面
     *
     * create by ck 20161216
     */
    public function resourcePackListAction()
    {
        $this->view->pick('res/resourcePackList');
        Assets::easyUI('js/res/resourcePackList.js');
        Assets::fileInput();
        Main::showNavPosition();
        UserPower::checkUserPower('Res_App_RPackList') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109103013));
        Template::exists('XHRes_ResourcePack', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109103014));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (UserPower::checkUserPower('Res_App_RPackList_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '增加', 'plain' => 'true', 'icon' => 'fa-plus'];
            $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '增加', 'class' => 'disabled'];
            $this->view->setVar('AddEdit', true);
        }
        if (UserPower::checkUserPower('Res_App_RPackList_Edit')) {
            $formButtonArr[] = ['id' => 'bt_form_edit', 'text' => '修改', 'class' => 'disabled'];
            $this->view->setVar('AddEdit', true);
        }
        if (UserPower::checkUserPower('Res_App_RPackList_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        if (UserPower::checkUserPower('Res_App_RPackList_Contact')) {
            $listButtonArr[] = ['id' => 'bt_list_ContactType', 'text' => '关联用户类型', 'plain' => 'true', 'icon' => 'fa-pencil'];
            $listButtonArr[] = ['id' => 'bt_list_ContactUser', 'text' => '关联用户', 'plain' => 'true', 'icon' => 'fa-pencil'];
            $listButtonArr[] = ['id' => 'bt_list_ContactGroup', 'text' => '关联应用组', 'plain' => 'true', 'icon' => 'fa-pencil'];
        }
        $formButtonArr[] = ['id' => 'bt_form_back', 'text' => '返回'];
        $formButtonArr[] = ['id' => 'bt_form_reset', 'text' => '重置'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'name' => 'list_search', 'label' => '搜索： '];
        $this->view->setVars([
            'List' => Template::createList('List', 'XHRes_ResourcePack', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form' => Template::createForm('XHRes_ResourcePack'),
            'FormButton' => Template::createButtonToolBar($formButtonArr)
        ]);
    }

    /**
     * 获取资源包记录
     *
     * create by ck 20161218
     */
    public function getRPackListAction()
    {
        $this->view->disable();
        $parameters = [
            'conditions' => 'bDelete = 0'
        ];
        Main::runSearchVagueConditions($parameters['conditions'], ['sRPName', 'sRPVersion', 'sSuffixName', 'tCreateDate']);
        $parameters['columns'] = 'iRPId,sRPName,sRPVersion,iSortCode,sSuffixName,mRPIntro,iRPSize,tCreateDate';
        $result = Main::runModelPaginator('\\Admin\\Models\\res\\XhresResourcepack', $parameters, true);
        Tool::runByteToMByte($result['rows'], 'iRPSize');
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 上传资源包并返回相应信息
     *
     * create by ck 20161218
     */
    public function uploadResPackAction()
    {
        set_time_limit(0);
        $this->view->disable();
        $this->request->hasFiles() or die;

        $appParseInfo = Main::getConfigByName('appParse');
        $filePath = $appParseInfo['tempPath'];
        $filePath or $filePath = '/Mailserver/cache/temp/';

        $data = [];
        foreach ($this->request->getUploadedFiles() as $file) {
            $fileName = $file->getName();

            $fileSuffix = explode('.', $fileName);
            $data['sRPName'] = $fileSuffix[0];
            $fileSuffix = end($fileSuffix);
            $data['sSuffixName'] = $fileSuffix;
            $data['iRPSize'] = $file->getSize();

            $fullPath = $filePath . $fileName;
            if (!is_writable($filePath)) {
                echo json_encode(['error' => "（109101013）路径{$filePath}无写入权限！"], JSON_UNESCAPED_UNICODE);
                die;
            }

            $file->moveTo($fullPath);
            $url = Main::uploadToFileManageSystem($fullPath, 'rPack', 'XHSVADTKBSCECK');
            if (!$url) {
                echo json_encode(['error' => '上传失败！'], JSON_UNESCAPED_UNICODE);
                die;
            }
            $data['sRPMd5'] = strtoupper(md5_file($fullPath));
            $data['sRPDownUrl'] = $url;

            @unlink($fullPath);
            echo json_encode($data, JSON_UNESCAPED_UNICODE);
            break;
        }
    }

    /**
     * 新增/修改资源包记录
     *
     * create by ck 20161218
     */
    public function modifyRPackDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $realData = Main::getRealData($this->request->getPost());
        $resPack = XhresResourcepack::createRecord($realData);
        $new = $resPack->iRPId ? false : true;
        UserPower::checkUserPower($new ? 'Res_App_RPackList_Add' : 'Res_App_RPackList_Edit')
        or die(Main::showMessageModal('无操作权限!', 109103015));
        $result = $new ? $resPack->insertData() : $resPack->updateData();
        $result or die(Main::showMessageModal('执行失败！', 109103016));
        Main::createCommitLog('res', 'ResourcePack', $new ? 'add' : 'edit', $resPack);
    }

    /**
     * 删除资源包记录
     *
     * create by ck 20161218
     */
    public function delRPackDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        UserPower::checkUserPower('Res_App_RPackList_Del') or die('（109103017）无删除权限！');
        $idArr = explode(',', $this->request->getPost('ids', 'string'));
        XhresResourcepack::deleteRecordById($idArr) or die('（109103018）删除失败！');
        echo '删除成功！';
        Main::createCommitLog('res', 'ResourcePack', 'del', ['ids' => $idArr], null, '批量删除');
    }

    /**
     * 根据应用编号获取关联的资源包信息
     *
     * create by ck 20161220
     */
    public function getContactRPackAction()
    {
        $this->view->disable();
        $appCode = $this->request->getPost('iAppCode', 'string');      //应用编号
        $type = $this->request->getPost('type', 'string');       //是否绑定
        $appCode && $type or die;
        $type == 'in' || $type = 'out' or die;
        $resPackIds = XhresResourcepackcontact::getResPackIdByAppCode($appCode);
        $parameters = [
            'conditions' => 'bDelete = 0',
            'columns' => 'iRPId,sRPName,sRPVersion,iSortCode,sSuffixName,mRPIntro,iRPSize,tCreateDate'
        ];
        if (!$resPackIds) {
            $type == 'in' and die(json_encode(['total' => 0, 'rows' => []]));
        } else {
            $type = ($type == 'in') ? 'IN' : 'NOT IN';
            $parameters['conditions'] .= " AND iRPId {$type} ({$resPackIds})";
        }
        $result = Main::runModelPaginator('\\Admin\\Models\\res\\XhresResourcepack', $parameters, true);
        Tool::runByteToMByte($result['rows'], 'iRPSize');
        $this->response->setJsonContent($result)->send();
    }

    /**
     * 设置应用与资源包 关联/取消关联
     *
     * create by ck 20161220
     */
    public function contactAppResPackAction()
    {
        $this->view->disable();
        $appCode = $this->request->getPost('iAppCode', 'string');
        $resPackIds = $this->request->getPost('resPackIds', 'string');
        $type = $this->request->getPost('type', 'string');
        $appCode && $resPackIds or die(Main::showMessageModal('缺少参数！', 109103023));
        $type == 'in' || $type == 'out' or die(Main::showMessageModal('类型错误！', 109103024));
        UserPower::checkUserPower('App_AppList_ContactRPack') or die(Main::showMessageModal('无操作权限！', 109103027));
        $resPackIdArr = explode(',', $resPackIds);
        $result = XhresResourcepackcontact::contactResPackToApp($resPackIdArr, $appCode, $type);
        $result or die(Main::showMessageModal('操作失败！', 109103025));
        $this->response->setContent('操作成功！')->send();
    }

    /**
     * 资源包与 用户类型/用户/应用组 关联/取消关联
     *
     * create by ck 20161219
     */
    public function setResPackPowerAction()
    {
        $this->view->disable();
        $resPackId = $this->request->getPost('iRPId', 'int');
        $target = $this->request->getPost('target', 'string');
        $values = $this->request->getPost('values', 'string');
        $type = $this->request->getPost('type', 'string');
        $resPackId && $target && $values && $type or die('（109103020）参数不完整！');
        $target == 'userType' || $target == 'userId' || $target == 'appGroup' or die('（109103021）目标类型不正确！');
        $type == 'in' || $type == 'out' or die('（109103022）操作类型不正确！');
        UserPower::checkUserPower('Res_App_RPackList_Contact') or die('（109103026）无操作权限！');
        $values = explode(',', $values);
        $result = false;
        switch ($target) {
            case 'userType':
                $result = XhresResourcepackusers::contactResPackToUserType($resPackId, $values, $type);
                break;
            case 'userId':
                $result = XhresResourcepackusers::contactResPackToUserId($resPackId, $values, $type);
                break;
            case 'appGroup':
                $result = XhresResourcepackusers::contactResPackToAppGroup($resPackId, $values, $type);
                break;
        }
        echo($type == 'out' ? '取消' : ''), '关联', ($result ? '成功' : '失败'), '！';
    }

    /**
     * 资源包关联用户类型页面
     *
     * create by ck 20161219
     */
    public function packContactUserTypeAction()
    {
        $resPackId = $this->request->getQuery('iRPId', 'int');
        $resPackId or die(Main::showMessageModal('无资源包ID', 109103019));
        $this->view->pick('res/packContactUserType');
        $this->assets->addCss('assets/bootstrap/bootstrap-switch.min.css', true)
            ->addCss('assets/toast/jquery.toast.css', true, true);
        $this->assets->addJs('assets/bootstrap/bootstrap-switch.min.js', true)
            ->addJs('assets/toast/jquery.toast.js', true, true);
        Assets::importJs('js/res/packContactUserType.js');
        $typeArr = XhsysEnum::getEnumByNodeName('用户类型');
        $userType = [];
        foreach ($typeArr as $typeKey => $typeValue) {
            $userType[$typeKey] = ['type' => $typeKey, 'name' => $typeValue];
        }
        $checkArr = XhresResourcepackusers::getContactUserType($resPackId);
        foreach ($checkArr as $typeValue) {
            $userType[$typeValue]['check'] = true;
        }
        $this->view->setVar('userType', array_values($userType));
    }

    /**
     * 资源包关联用户页面
     *
     * create by ck 20161221
     */
    public function packContactUserIdAction()
    {
        $resPackId = $this->request->getQuery('iRPId', 'int');
        $resPackId or die(Main::showMessageModal('无资源包ID', 109103019));
        $this->view->pick('res/packContactUserId');
        Assets::easyUI('js/res/packContactUserId.js');
        UserPower::checkUserPower('Res_App_RPackList_Contact') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109103028));
        Template::exists('XHSys_User', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109103029));
        $this->view->setVars([
            'InList' => Template::createList('InList', 'XHSys_User', [
                'title' => '已关联用户',
                'field' => ['iUserId', 'sLogonName', 'sUserName', 'sAdClsName', 'sSelfPhone', 'iUserType', 'iUserSex']
            ]),
            'NotList' => Template::createList('OutList', 'XHSys_User', [
                'title' => '未关联用户',
                'field' => ['iUserId', 'sLogonName', 'sUserName', 'sAdClsName', 'sSelfPhone', 'iUserType', 'iUserSex']
            ]),
        ]);
    }

    /**
     * 获取资源包关联/未关联用户信息
     *
     * create by ck 20161221
     */
    public function getPackContactUserDataAction()
    {
        $this->view->disable();
        $resPackId = $this->request->getPost('iRPId', 'int');
        $type = $this->request->getPost('type', 'string');
        $resPackId && $type or die;
        $type == 'in' || $type == 'out' or die;
        $userIds = XhresResourcepackusers::getUserIdByResPackId($resPackId);
        $parameters = [
            'conditions' => 'bDelete = 0 AND bDisable = 0',
            'columns' => 'iUserId,sLogonName,sUserName,sAdClsName,sSelfPhone,iUserType,iUserSex'
        ];
        if (!$userIds) {
            $type == 'in' and die(json_encode(['total' => 0, 'rows' => []]));
        } else {
            $type = ($type == 'in') ? 'IN' : 'NOT IN';
            $parameters['conditions'] .= " AND iUserId {$type} ({$userIds})";
        }
        echo Main::runModelPaginator('\\Admin\\Models\\user\\XhsysUser', $parameters);
    }

    /**
     * 资源包关联用户页面
     *
     * create by ck 20161221
     */
    public function packContactAppGroupAction()
    {
        $resPackId = $this->request->getQuery('iRPId', 'int');
        $resPackId or die(Main::showMessageModal('无资源包ID', 109103030));
        $this->view->pick('res/packContactAppGroup');
        Assets::easyUI('js/res/packContactAppGroup.js');
        Assets::select2();
        UserPower::checkUserPower('Res_App_RPackList_Contact') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109103031));
        Template::exists('XHSchool_AppGroup', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109103032));
        $this->view->setVars([
            'InList' => Template::createList('InList', 'XHSchool_AppGroup', [
                'title' => '已关联应用组',
                'field' => ['iSAGId', 'sSchoolName', 'sSAGName', 'iSAType']
            ]),
            'NotList' => Template::createList('OutList', 'XHSchool_AppGroup', [
                'title' => '未关联应用组',
                'field' => ['iSAGId', 'sSchoolName', 'sSAGName', 'iSAType']
            ]),
            'schoolList' => XhschoolInfo::getSchoolArray()
        ]);
    }

    /**
     * 获取资源包关联/未关联应用组信息
     *
     * create by ck 20161221
     * modify by ck 20161222    添加学校ID筛选
     */
    public function getPackContactGroupDataAction()
    {
        $this->view->disable();
        $resPackId = $this->request->getPost('iRPId', 'int');
        $type = $this->request->getPost('type', 'string');
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $resPackId && $type or die;
        $type == 'in' || $type == 'out' or die;
        $userIds = XhresResourcepackusers::getAppGroupIdByResPackId($resPackId);
        $parameters = [
            'conditions' => 'bDelete = 0 AND bSAGEnable = 1',
            'columns' => 'iSAGId,sSAGName,iSAType,iSchoolId'
        ];
        if ($schoolId) {
            $parameters['conditions'] .= " AND iSchoolId = {$schoolId}";
        }
        if (!$userIds) {
            $type == 'in' and die(json_encode(['total' => 0, 'rows' => []]));
        } else {
            $type = ($type == 'in') ? 'IN' : 'NOT IN';
            $parameters['conditions'] .= " AND iSAGId {$type} ({$userIds})";
        }
        $result = Main::runModelPaginator('\\Admin\\Models\\school\\XhschoolAppgroup', $parameters, true);
        XhschoolInfo::runSchoolName($result['rows']);
        $this->response->setJsonContent($result)->send();
    }


    /**
     * 方法说明 :获取分类
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * Created by zsc
     */
    public function getClassifyAction(){
        $classifyType = $this->request->get('classifyType', 'string');
        $result = Books::getEnumTypeList();
        $classifyArr = [
            'grade'     => '年级',
            'subject'   => '科目',
        ];
        if($result)foreach ($result as $key => $value){
            if($value['paramType'] == strtolower($classifyType)){
                $data[] = [
                    'classifyId'        => $value['id'],
                    'classifyName'      => $value['name'],
                    'typeName'          => $classifyArr[$value['paramType']],
                    'typeTag'           => $value['paramType'],
                ];
            }
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 导出题库为word页面
     *
     * create by ck 20170804
     */
    public function exportExamToWordAction()
    {
        $this->view->pick('res/exportExamToWord');
        Main::showNavPosition();
        Assets::importJs('js/res/exportExamToWord.js');
    }

    /**
     * 题库字数统计
     *
     * create by ck 20170804
     */
    public function examCharStatAction()
    {
        set_time_limit(0);
        $this->view->pick('res/examCharStat');
        Main::showNavPosition();
        if (!UserPower::checkUserPower('Res_QBank_CharStat')) {
            return $this->sendViewError('无操作权限！');
        }
        if (!$this->request->isPost()) {
            return $this->flash->notice('请输入题库ID并执行统计...');
        }
        $examId = $this->request->getPost('examId', 'string');
        $imgCost = $this->request->getPost('imgCost', 'int');
        if (!$examId) return true;
        $total = $tree = $tmpTree = [];
        try {
            //2.0题库
            if (is_numeric($examId)) {
                $dbConfig = Main::getConfigByName('oldCenterDB');
                $dbConfig['dbname'] .= '_exam' . $examId;
                $conn = new Mysql($dbConfig);
                $treeArr = $conn->fetchAll('SELECT ad_id1 as id,ad_name as name,ad_parentid as parentId FROM address_items_tree_user');

                $this->dealExamTree($tmpTree, $treeArr);
                $this->sortExamTree($tree, $tmpTree);
                $tree = array_column($tree, null, 'id');
                while ($queArr = $this->getExamQuestion($conn)) {
                    foreach ($queArr as $que) {
                        //计算题目数量
                        @$tree[$que['treeId']]['que']++;
                        @$total['que']++;

                        //检查图片数量
                        $imgCount = 0;
                        preg_match_all("/<img.*?src=\"(\.\.\/.*?)\".*?>/i", $que['content'], $imgInfo);
                        if (!empty($imgInfo[0])) {
                            $imgCount = count($imgInfo[0]);
                            @$tree[$que['treeId']]['img'] += $imgCount;
                            @$total['img'] += $imgCount;
                        }

                        //计算字符数
                        $content = strip_tags($que['content']);
                        $content = str_replace('[答案始]', '', $content);
                        $content = str_replace('[/答案终]', '', $content);
                        $content = str_replace('[详解始]', '', $content);
                        $content = str_replace('[/详解终]', '', $content);
                        $content = str_replace('&nbsp;', ' ', $content);
                        $length = mb_strlen($content, 'utf8');
                        @$tree[$que['treeId']]['char'] += $length;
                        @$total['char'] += $length;

                        //去除空格字符数
                        $length = mb_strlen(str_replace(' ', '', $content), 'utf8');
                        @$tree[$que['treeId']]['charReal'] += $length;
                        @$total['charReal'] += $length;

                        //图片折合字符数
                        if ($imgCost && $imgCount) {
                            @$tree[$que['treeId']]['imgChar'] += $imgCost * $imgCount;
                            @$total['imgChar'] += $imgCost * $imgCount;
                        }
                    }
                }
            } //3.0题库
            else {
                $url = Main::getConfigByName('exam')['url'];
                if (!$url) {
                    return $this->flash->error('缺少配置信息！');
                }
                $httpClient = new HttpClient($url);
                $response = $httpClient->get('/api/v1/questions/bookWordCount', ['bookId' => $examId, 'conversionRate' => $imgCost]);
                if (!$response->isSuccess()) {
                    return $this->flash->error('请求失败：' . json_encode($response, JSON_UNESCAPED_UNICODE));
                }
                $body = $response->toArray();
                foreach ($body['dirList'] as $row) {
                    $tree[] = [
                        'name' => $row['title'],
                        'que' => $row['topicNum'],
                        'char' => $row['charNum'],
                        'charReal' => $row['realCharNum'],
                        'img' => $row['imgNum'],
                        'imgChar' => $row['imgChar'],
                    ];
                }
                $total = [
                    'que' => $body['total']['topicNum'],
                    'char' => $body['total']['charNum'],
                    'charReal' => $body['total']['realCharNum'],
                    'img' => $body['total']['imgNum'],
                    'imgChar' => $body['total']['imgChar'],
                ];
            }
        } catch (\Exception $e) {
            return $this->flash->error($e->getMessage());
        }
        $this->view->setVars([
            'tree' => $tree,
            'total' => $total
        ]);
        return true;
    }

    /**
     * 处理目录树
     *
     * @param $tree
     * @param $title
     *
     * create by ck 20170804
     */
    private function dealExamTree(&$tree, &$title)
    {
        if (empty($tree)) {
            foreach ($title as $key => $val) {
                if ($val['parentId'] == 0) {
                    $tree[] = ['id' => intval($val['id']), 'name' => $val['name']];
                    unset($title[$key]);
                    $this->dealExamTree($tree, $title);
                }
            }
        } else {
            foreach ($tree as $treeKey => $treeVal) {
                foreach ($title as $key => $val) {
                    if ($val['parentId'] == $treeVal['id']) {
                        $tree[$treeKey]['child'][] = ['id' => intval($val['id']), 'name' => $val['name']];
                        unset($title[$key]);
                    }
                }
                if (isset($tree[$treeKey]['child'])) {
                    $this->dealExamTree($tree[$treeKey]['child'], $title);
                }
            }
        }
    }

    /**
     * 目录树改为一维数组
     *
     * @param $newTree
     * @param $treeArr
     * @param string $link
     *
     * create by ck 20170804
     */
    private function sortExamTree(&$newTree, $treeArr, $link = '')
    {
        $newLink = $link . '&#12288;&#12288;';
        foreach ($treeArr as $tree) {
            $temp = $tree;
            unset($temp['child']);
            $temp['que'] = $temp['img'] = $temp['char'] = $temp['charReal'] = $temp['imgChar'] = '';
            $temp['name'] = $link . $temp['name'];
            $newTree[] = $temp;
            if (isset($tree['child'])) {
                $this->sortExamTree($newTree, $tree['child'], $newLink);
            }
        }
    }

    /**
     * 获取题目信息
     *
     * @param Mysql $conn
     * @return array
     *
     * create by ck 20170804
     */
    private function getExamQuestion(Mysql $conn)
    {
        static $offset = 0, $rows = 20;
        $queArr = $conn->fetchAll("select ho_ad_id as treeId,ho_zycontent as content from homework_list_base where ho_zycontent <> '' and ho_status=1 and ho_parent_id = 0 and ho_tmpflag = 0 limit {$offset},{$rows}");
        $offset += $rows;
        return $queArr;
    }

    /**
     * 资源库枚举
     * create by wy 20180129
     */
    private $schEnum = [
        'iStatus' => [1 => '同步书', 8 => '专题书', 9 => '引用书'],
    ];

    /**
     * 枚举
     *
     * @return mixed
     *
     * create by qgz 2018/5/9
     */
    public function getEnumTypeList()
    {
        $books = new Books();
        $data = $books->getEnumTypeList();
        $fina = [];
        if ($data) {
            foreach ($data as $value) {
                if ($value['paramType'] == 'textBookVersion') {
                    $fina['book'][$value['id']] = $value['name'];
                } elseif ($value['paramType'] == 'grade') {
                    $fina['grade'][$value['id']] = $value['name'];
                } elseif ($value['paramType'] == 'subject') {
                    $fina['subject'][$value['id']] = $value['name'];
                }
            }
        }
        return $fina;
    }

    /**
     * 资源库列表
     *
     * @return \Phalcon\Mvc\View
     * @throws \Exception
     * @throws \Lybc\PhpGB2260\InvalidCodeException
     *
     * create by wy 20180129
     * modify by qgz 20190226 //云教辅页面
     */
    public function synResListAction()
    {
        $this->view->pick('res/synResList');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI();
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        Assets::easyUI('js/res/synResList.js');
        $cloudBook = $this->request->getQuery('cloudBook');//云教辅页面
        if (!UserPower::checkUserPower('Res_QBank_Syn') && !$cloudBook) {
            return $this->sendViewError('无查看权限');
        }
        $listButtonArr = $formButtonArr = $listSearchArr = [];
        $bookTypeEnum = ['' => '请选择'] + $this->schEnum['iStatus'];
        unset($bookTypeEnum[9]);
        $enumType = $this->getEnumTypeList();
        if ($cloudBook) {
            $enum = ['' => '--请选择--'];
            $enumProvence = ['' => '--请选择--'] + $this->getEnumProvence();
        } else {
            $enum = ['' => '--请选择--'] + $enumType['grade'];
            $enumProvence = ['' => '--请选择--'];
        }
        if (!$cloudBook) {
            $listSearchArr[] = array('type' => 'select', 'id' => 'list_search_status', 'data' => $bookTypeEnum);
        }
        if ($cloudBook) {
            $listSearchArr[] = array('label' => ' 省：','type' => 'select', 'id' => 'list_search_province', 'data' => $enumProvence);
            $listSearchArr[] = array(
                'label' => ' 市：','type' => 'select', 'id' => 'list_search_city', 'data' => ['' => '--请选择--']);
            $listSearchArr[] = array(
                'label' => ' 区：','type' => 'select', 'id' => 'list_search_country', 'data' => ['' => '--请选择--']);
        }
        $listSearchArr[] = array('label' => ' 年级：','type' => 'select', 'id' => 'list_search_grade', 'data' => $enum);
        $listSearchArr[] = array(
            'label' => ' 科目：','type' => 'select', 'id' => 'list_search_subject', 'data' => ['' => '--请选择--']);
        $listSearchArr[] = array(
            'label' => ' 教材：','type' => 'select', 'id' => 'list_search_book', 'data' => ['' => '--请选择--']);
        if (!$cloudBook) {
            $listSearchArr[] = array(
                'label' => ' ', 'type' => 'select', 'id' => 'list_search_apply', 'data' => ['' => '--教辅申请--'] + $this->referenceApply);
            $listSearchArr[] = array(
                'label' => ' ', 'type' => 'select', 'id' => 'list_search_bookNature', 'data' => ['' => '--云教辅--'] + [1 => '是']);
        }
        $listSearchArr[] = array(
            'label' => ' 搜索：','type' => 'select', 'id' => 'list_search_type', 'data' => ['' => '书名', 1 => '书id'], 'style' => 'width:60px');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search_vague');
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
                            'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出',
                            'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];

        if (!$cloudBook) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_contact_school', 'text' => '查看学校',
                                     'icon' => 'fa-graduation-cap');
            if (Power::exist('Res_QBank_Syn_Add')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_contact', 'text' => '关联教师', 'icon' => 'fa-pencil');
            }
            if (Power::exist('Res_QBank_Syn_Apply')) {
                $listButtonArr[] = ['id' => 'bt_list_referenceAllow', 'class' => 'menubutton', 'text' => '教辅申请', 'plain' => 'true', 'icon' => 'fa-puzzle-piece'];
            }
            $xmlName = 'XHRes_SynRes';
        } else {
            $xmlName = 'XHRes_CloudBook';
        }
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_use_info', 'text' => '使用情况', 'icon' => 'fa-bars');
        return $this->view->setVars(array(
            'List' => Template::createList('list', $xmlName, [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form' => Template::createForm('XHSchool_Info', $this->schEnum),
            'FormButton' => Template::createButtonToolBar(Main::createFormButton('Res_QBank_Syn'))
        ));
    }

    /**
     * 资源库new列表
     * create by qgz 20180425
     * modify by qgz 20180510 增加筛选类型
     * modify by qgz 20180525 去掉类型筛选
     */
    public function newResListAction()
    {
        $this->view->pick('res/newResList');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/res/newResList.js');
        if (!Power::exist('Res_QBank_SynNew')) {
            return $this->sendViewError('无查看权限');
        }
        $enumType = $this->getEnumTypeList();
        $enum = ['' => '--请选择--'] + $enumType['grade'];
        $listButtonArr = $formButtonArr = $listSearchArr = [];
        if (Power::exist('Res_ReferenceApply_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '教辅申请', 'plain' => 'true', 'icon' => 'fa-plus'];
        }
        if (Power::exist('Res_ReferenceRepeal_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_back', 'text' => '申请撤销', 'plain' => 'true', 'icon' => 'fa-undo'];
        }
        $listSearchArr[] = array('label' => ' 年级：','type' => 'select', 'id' => 'list_search_grade', 'data' => $enum);
        $listSearchArr[] = array(
            'label' => ' 科目：','type' => 'select', 'id' => 'list_search_subject', 'data' => ['' => '--请选择--']);
        $listSearchArr[] = array(
            'label' => ' 教材：','type' => 'select', 'id' => 'list_search_book', 'data' => ['' => '--请选择--']);
        $listSearchArr[] = ['label' => ' 应用：', 'type' => 'select', 'id' => 'list_search_app',
                            'data' => ['com.xh.abrutch' => '学海题舟', 'com.xh.acldtch' => '云作业']];
        $listSearchArr[] = array(
            'label' => ' 搜索：','type' => 'select', 'id' => 'list_search_type', 'data' => ['' => '书名', 1 => '书id'], 'style' => 'width:60px');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search_vague');
        return $this->view->setVars(array(
            'List' => Template::createList('list', 'XHRes_NewRes', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form' => Template::createForm('XHSchool_Info', $this->schEnum),
            'FormButton' => Template::createButtonToolBar(Main::createFormButton('Res_QBank_Syn'))
        ));
    }

    /**
     * 获取搜索框选项联动数据
     *
     * @return string
     *
     * create by qgz 20180525
     */
    public function getSearchDataAction()
    {
        $type = $this->request->getQuery('type');
        $grade = $this->request->getQuery('grade');
        $subject = $this->request->getQuery('subject');
        $books = new Books();
        $allData = $books->getBookData();
        $valueNameArr = $this->getEnumTypeList();
        $return[] = ['value' => '', 'text' => '--请选择--'];
        if (empty($allData) || empty($valueNameArr)) {
            return json_encode($return);
        }
        if ($type == 1) {//根据grade值获取project数据
            $inSubject = [];
            foreach ($allData as $value) {
                if ($value['gradeId'] == $grade && !in_array($value['subjectId'], $inSubject)) {
                    $return[] = [
                        'value' => $value['subjectId'],
                        'text' => $valueNameArr['subject'][$value['subjectId']]];
                    $inSubject[] = $value['subjectId'];
                }
            }
            return json_encode($return);
        } else {//根据project值获取book数据
            $inBook = [];
            if ($subject) {
                foreach ($allData as $value) {
                    if ($value['gradeId'] == $grade && $value['subjectId'] == $subject &&
                        !in_array($value['textBookVersion'], $inBook)) {
                        $return[] = [
                            'value' => $value['textBookVersion'],
                            'text' => $valueNameArr['book'][$value['textBookVersion']]
                        ];
                        $inBook[] = $value['textBookVersion'];
                    }
                }
            }
            return json_encode($return);
        }
    }

    /**
     * 获取所有省份数据
     *
     * @return array
     * @throws \Exception
     * @throws \Lybc\PhpGB2260\InvalidCodeException
     *
     * create by qgz 20190226
     */
    public function getEnumProvence()
    {
        $areaObj = new Area();
        return $areaObj->getAllProvinces(true);
    }

    /**
     * 获取搜索框地区联动数据
     *
     * @return string
     * @throws \Exception
     *
     * create by qgz 20190226
     */
    public function getAreaDataAction()
    {
        $type = $this->request->getQuery('type');
        $province = $this->request->getQuery('province');
        $city = $this->request->getQuery('city');
        $return[] = ['value' => '', 'text' => '--请选择--'];
        if (!$type) {
            return json_encode($return);
        }
        $areaObj = new Area();
        if ($type == 1) {//根据省获取市的数据
            $dataArr = $areaObj->getCityByProId($province, true);
        } else {//根据市获取县的数据
            $dataArr = $areaObj->getCountryByProId($city, true);
        }
        if (!$dataArr) {
            return json_encode($return);
        }
        foreach ($dataArr as $key => $value) {
            $return[] = ['value' => $key, 'text' => $value];
        }
        return json_encode($return);
    }

    /**
     * 根据区域获取年级教材版本数据
     *
     * @return string
     * @throws \Exception
     * @throws \Helpers\XhException
     *
     * create by qgz 20190227
     */
    public function getBookByAreaAction()
    {
        $return[] = ['value' => '', 'text' => '--请选择--'];
        $pro = $this->request->getQuery('prov');
        $city = $this->request->getQuery('city');
        $country = $this->request->getQuery('country');
        $type = $this->request->getQuery('type');
        $area = [];
        if ($pro) {
            $areaObj = new Area((int)$pro);
            $area['provinceName'] = $areaObj->getCurrent();
        }
        if ($city) {
            $areaObj = new Area((int)$city);
            $area['cityName'] = $areaObj->getCurrent();
        }
        if ($country) {
            $areaObj = new Area((int)$country);
            $area['districtName'] = $areaObj->getCurrent();
        }
        $data = ResAreaGroup::getAreaGroupList(1, 10000, '', $area);
        if (empty($data)){
            return json_encode($return);
        }
        $data = isset($data['groupInfoListResponseList']) ? $data['groupInfoListResponseList'] : [];
        if (!$data) {
            return json_encode($return);
        }
        $idArr = [];
        $enumTypeKey = '';
        $groupIdArr = array_column($data, 'groupId');
        foreach ($groupIdArr as $groupId) {
            $data = ResAreaGroup::getSubVerById($groupId);
            if (!$data) {
                continue;
            }
            $key = $enumTypeKey = '';
            switch ($type) {
                case 1:
                    $key = 'gradeId';
                    $enumTypeKey = 'grade';
                    break;
                case 2:
                    $key = 'subjectId';
                    $enumTypeKey = 'subject';
                    break;
                case 3:
                    $key = 'textBookVersion';
                    $enumTypeKey = 'book';
                    break;
                default:
                    break;
            }
            if ($key) {
                $idArr = array_unique(array_merge($idArr, array_column($data, $key)));
            }
        }
        if ($idArr) {
            $idArr = array_filter($idArr);
            $enumType = $this->getEnumTypeList();
            foreach ($idArr as $id) {
                if ($enumTypeKey) {
                    $return[] = ['value' => $id, 'text' => $enumType[$enumTypeKey][$id]];
                }
            }
        }
        return json_encode($return);
    }

    /**
     * 资源库根据页码及每页行数获取书本数据并以json格式返回
     *
     * @param bool $isExport
     * @param array $params
     *
     * @return mixed|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by wy 20180130
     * modify by qgz 20180525 使用同一接口
     * modify by qgz 20180911 使用新接口、导出excel
     */
    public function getBookListAction($isExport = false, $params = [])
    {
        $this->view->disable();
//        $status = $this->request->getPost('status', 'int');
        $searchArr = $this->request->getPost('search');
        $searchType = $this->request->getPost('searchType');
        $book = $this->request->getPost('book');
        $grade = $this->request->getPost('grade');
        $subject = $this->request->getPost('subject');
        $status = $this->request->getPost('status');
        $referApply = $this->request->getPost('referApply');
        $bookNature = $this->request->getPost('bookNature');
        $cloudBook = $this->request->getPost('cloudBook');
        $dictionaries = new Dictionaries();
        $enumArr = $dictionaries->runDictionariesData();

        if ($isExport) {//导出excel
            $searchArr['vague'] = $params['search'];
            $searchType = $params['searchType'];
            $book = $params['book'];
            $grade = $params['grade'];
            $subject = $params['subject'];
            $status = $params['status'];
            $bookNature = $params['bookNature'];
            $cloudBook = $params['cloudBook'];
            $referApply = $params['referApply'];
        }
        if ($cloudBook && !$grade && !$subject && !$book) {
            if ($isExport) {
                return [];
            }
            return $this->response->setJsonContent(['total' => 0, 'rows' => []]);
        }
        $getArr = array(
            'page' => Main::getPageNumInfo('page'),
            'size' => Main::getPageNumInfo('rows'),
            'libraryType' => $status,
            'gradeId' => $grade,
            'subjectId' => $subject,
            'textBookVersion' => $book
        );
        if ($referApply !== '') {
            $getArr['bookSecurity'] = $referApply;
        }
        if ($searchType) {//书id
            $getArr['bookId'] = $searchArr['vague'] ? $searchArr['vague'] : '';
        } else {
            if ($searchArr['vague']) {
                $getArr['bookName'] = $searchArr['vague'];
            }
        }
        if ($bookNature || $cloudBook) {//是否是云教辅
            $getArr['bookNature'] = 1;
        }
        if ($isExport) {
            $getArr['page'] = $params['page'];
            $getArr['size'] = $params['rows'];
        }
        $books = new Books();
//        $result = $books->getAllBookList($getArr);
        $result = $books->getNewAllBookList($getArr);
        $data = ['total' => 0, 'rows' => []];
        $libraryTypeEnum = $this->schEnum['iStatus'];
        $libraryTypeEnum[9] = '专题书';//类型9（引用书）也当做专题书
        if (!empty($result)) {
            $data['total'] = $result[0]['totalCount'];
            foreach ($result as $value) {
                $dataArr = [
                    'bookId' => $value['bookId'],
                    'bookName' => $value['bookName'],
                    'count' => $value['bookCount'],
                    'libraryType' => $libraryTypeEnum[$value['libraryType']],
                    'subject' => isset($enumArr['subject'][$value['subjectId']]) ?
                        $enumArr['subject'][$value['subjectId']] : '',
                    'usedSchoolCount' => $value['usedSchoolCount'],
                    'extra' => '',
                    'bookSecurity' => $this->referenceApply[$value['bookSecurity']]
                ];
                if (($value['libraryType'] == 8 || $value['libraryType'] == 9) && !$isExport) {//专题书
                    $dataArr['extra'] = $this->addExtraData($value['textBookDTOList'], $enumArr);
                } elseif ($value['libraryType'] == 1 && $value['textBookDTOList']) {//同步书
                    if (isset($value['textBookDTOList'][0])) {
                        $detail = $value['textBookDTOList'][0];
                        $dataArr['grade'] = isset($enumArr['grade'][$detail['gradeId']]) ?
                            $enumArr['grade'][$detail['gradeId']] : '';
                        $dataArr['textBookVersion'] = isset($enumArr['textBookVersion'][$detail['textBookVersion']]) ?
                            $enumArr['textBookVersion'][$detail['textBookVersion']] : '';
                    }
                }
                $data['rows'][] = $dataArr;
            }
        }
        if ($isExport) {
            return $data['rows'];
        }
        return $this->response->setJsonContent($data);
    }

    /**
     * 添加专题书详情
     *
     * @param $dataArr
     * @param $enum
     *
     * @return string
     *
     * create by qgz 20180911
     */
    public function addExtraData($dataArr, $enum)
    {
        $return = '';
        if (!$dataArr) {
            return $return;
        }
        $return = '<table><tr>' .
                  '<th style="text-align: center">年级</th>' .
                  '<th style="text-align: center">学科</th>' .
                  '<th style="text-align: center">教材</th></tr>';
        foreach ($dataArr as $value) {
            if ($value) {
                $return .= '<tr><td style="width: 100px;">' . $enum['grade'][$value['gradeId']] . '</td>' .
                           '<td style="width: 100px">' . $enum['subject'][$value['subjectId']] . '</td>' .
                           '<td style="width: 100px">' . $enum['textBookVersion'][$value['textBookVersion']] . '</td>' .
                           '</tr>';
            }
        }
        $return .= '</table>';
        return $return;
    }

    public function exportExcelAction()
    {
        $this->view->disable();
        try {
            $params['status'] = $this->request->getQuery('status');
            $params['search'] = $this->request->getQuery('search');
            $params['searchType'] = $this->request->getQuery('searchType');
            $params['referApply'] = $this->request->getQuery('referApply');
            $params['book'] = $this->request->getQuery('book');
            $params['grade'] = $this->request->getQuery('grade');
            $params['subject'] = $this->request->getQuery('subject');
            $params['bookNature'] = $this->request->getQuery('bookNature');
            $params['cloudBook'] = $this->request->getQuery('cloudBook');
            $params['page'] = $this->request->getQuery('page');
            $params['rows'] = $this->request->getQuery('rows');
            $dataArr = $this->getBookListAction(true, $params);

            $title = [
                'bookName' => '书名',
                'count' => '题数',
                'libraryType' => '类型',
                'grade' => '年级',
                'subject' => '学科',
                'textBookVersion' => '教材',
                'usedSchoolCount' => '学校数量'
            ];
            $data = [];
            foreach ($dataArr as $value) {
                $row = [];
                foreach ($title as $filed => $name) {
                    $row[$filed] = Tool::getValue($value, $filed);
                }
                $data[] = $row;
            }
            $fileName = '资源库数据表';
            $otherParams = ['autoWidth' => true, 'header' => ['title' => '资源库数据表']];
            Tool::exportExcelOnline($fileName, $title, $data, 'xlsx', $otherParams);
            return true;
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 新资源库，根据页码及每页行数获取书本数据并以json格式返回
     * create by qgz 20180425
     * modify by qgz 20180510 增加搜索类型，使用新接口
     * modify by qgz 20180525 使用同一接口
     * modify by qgz 20180529 去掉名字精确搜索
     */
    public function getNewBookListAction()
    {
        $this->view->disable();
        $type = $this->request->getPost('type', 'int');
        $book = $this->request->getPost('book');
        $grade = $this->request->getPost('grade');
        $subject = $this->request->getPost('subject');
        $searchArr = $this->request->getPost('search');
        $searchType = $this->request->getPost('search_type');
        $app = $this->request->getPost('app');
        if ($type == 1) {
            return $this->response->setJsonContent(['total' => 0, 'rows' => []]);
        }
        $dictionaries = new Dictionaries();
        $dictionariesArr = $dictionaries->runDictionariesData();
        $book = ($book == '--请选择--') ? '' : $book;
        $subject = ($subject == '--请选择--') ? '' : $subject;
        $getArr = array(
            'page' => Main::getPageNumInfo('page'),
            'size' => Main::getPageNumInfo('rows'),
            'textBookVersion' => $book,
            'gradeId' => $grade,
            'subjectId' => $subject,
            'packageName' => $app,
            'userId' => 0,
            'publishStatus' => 0,
//            'bookName' => $searchArr['vague'] ? $searchArr['vague'] : null,
            'bookSecurity' => 1 //教辅申请，允许
        );
        if (!$searchType) {//模糊搜书名
            $getArr['bookName'] = $searchArr['vague'] ? $searchArr['vague'] : '';
        } else  {//精确搜书id
            $getArr['bookId'] = $searchArr['vague'] ? $searchArr['vague'] : '';
        }

        $books = new Books();
        $result = $books->getAllBookList($getArr);
        $data = array();
        if (!empty($result)) {
            $data['rows'] = [];
            $host = Main::getConfigByName('res');
            foreach ($result['bookClientDTOList'] as $value) {
//                if ($this->matchName(trim($searchArr['vague']), $value['bookName'])){//完全匹配书名(带括号的去掉括号后完全匹配)
                    $data['rows'][] = array(
                        'bookId' => $value['bookId'],
                        'bookName' => $value['bookName'],
                        'count' => $value['count'],
                        'libraryType' => $this->schEnum['iStatus'][$value['libraryType']],
                        'grade' => isset($dictionariesArr['grade'][$value['gradeId']]) ? $dictionariesArr['grade'][$value['gradeId']] : '',
                        'subject' => isset($dictionariesArr['subject'][$value['subjectId']]) ? $dictionariesArr['subject'][$value['subjectId']] : '',
                        'textBookVersion' => isset($dictionariesArr['textBookVersion'][$value['textBookVersion']]) ? $dictionariesArr['textBookVersion'][$value['textBookVersion']] : '',
                        'progress' => '<div><a bookId="'.$value['bookId'].'" '.'host="'.$host['outsideUrl'].'"'.' class="progress">点击查看</a></div>',
                        'gradeId' => $value['gradeId'],
                        'subjectId' => $value['subjectId'],
                        'status' => $this->registerEnum['resStatus'][$value['publishStatus']]
                    );
//                }
            }
            $data['total'] = count($data['rows']);
        }
        return $this->response->setJsonContent($data);
    }

    /**
     * 匹配书名，规则：去掉括号及括号以后出现的字符和书名进行比较，然后完全匹配
     *
     * @param $searchName
     * @param $strName
     *
     * @return bool
     *
     * create by qgz 2018/4/25
     */
    public function matchName($searchName, $strName)
    {
        if (!$searchName) {
            return false;
        }
        if ($searchName == $strName) {
            return true;
        }
        $leng  = strpos($strName, '(');
        $leng2 = strpos($strName, '（');
        if ($leng !== false || $leng2 !== false) {
            if ($searchName == substr_replace($strName, '', $leng)) {
                return true;
            }
            if ($searchName == substr_replace($strName, '', $leng2)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 教师与书本关联页面
     * create by wy 20180131
     */
    public function teacherContactBookAction()
    {
        $this->view->pick('res/teacherContactBook');
        if (!UserPower::checkUserPower('Res_QBank_Syn')) {
            return $this->sendViewError('无关联权限');
        }
        Assets::select2();
        Assets::easyUI('js/res/teacherContactBook.js');
        $subjectArr = array('0' => "--选择学科--");
        $dictionaries = new Dictionaries();
        $dictionariesArr = $dictionaries->runDictionariesData();
        $subjectArr = array_merge($subjectArr, $dictionariesArr['subject']);
        $schoolBase = new SchoolBase();
        $getArr = array(
            'page' => 0,
            'size' => 1000,
        );
        $result = $schoolBase->getSchools($getArr);
        $schoolIds = array();
        if (!empty($result)) {
            foreach ($result['content'] as $value) {
                $schoolIds[$value['id']] = $value['name'];
            }
        }
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_type', 'data' => [1 => '登录名',2 => '姓名'], 'default' => 1);
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px' );
        $this->view->setVars(array(
            'nav' => $this->request->getQuery('nav', 'string'),
            'bookId' => $this->request->getQuery('bookId', 'string'),
            'schoolIds' => $schoolIds,
            'subjectIds' => $subjectArr,
            'InList' => Template::createList('InList', 'XHRes_TeacherBookIn', array('title' => '已关联教师', 'searchToolbar' => Template::createSearchToolBar($listSearchArr, false))),
            'NotList' => Template::createList('OutList', 'XHRes_TeacherBookOut', array('title' => '未关联教师')),
        ));
    }

    /**
     * 修改书本的是否可申请教辅排期
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181024
     */
    public function setBookSecurityAction()
    {
        $bookId = $this->request->getPost('bookId');
        $bookSecurity = $this->request->getPost('bookSecurity');
        if (!$bookId || !in_array($bookSecurity, [0, 1])) {
            return $this->sendErrorResponse(400, '书本id为空或设置类型不正确');
        }
        try {
            $params = [
                'bookSecurity' => $bookSecurity,
                'modifyUserId' => User::getId()
            ];
            $books = new Books();
            $books->modifyBook($bookId, $params);
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 根据学校的学科获取教师列表
     * create by wy 20180201
     */
    public function getTeacherListAction()
    {
        $this->view->disable();
        $dataType = $this->request->getPost('type', 'string');
        $dictionaries = new Dictionaries();
        $dictionariesArr = $dictionaries->runDictionariesData();
        $data = array();
        $data['rows'] = [];
        $data['total'] = 0;
        if ($dataType == 'in') {
            $bookId = $this->request->getPost('bookId', 'string');
            $key    = $this->request->getPost('key','string');
            $searchType = $this->request->getPost('searchType','int');
            $getArr = array(
                'bookId' => $bookId,
                'page' => Main::getPageNumInfo('page'),
                'size' => Main::getPageNumInfo('rows'),
            );
            if ($key && $searchType) {  //搜索一种名称
                if ($searchType == 1) {
                    $getArr['logonName'] = $key ;
                } else if ($searchType == 2) {
                    $getArr['userName']  = $key ;
                } else {
                    return $this->sendErrorResponse(500, '搜索类型不匹配');
                }
            }
            $questionPrivilege = new QuestionPrivilege();
            $result = $questionPrivilege->getBookScopeUser($getArr);
            if (!empty($result)) {
                $data['total'] = $result['totalCount'];

                if(isset($result['userDTOList'])  && count($result['userDTOList'])>0 ){
                    $ids = array_column($result['userDTOList'],'userId');
                    $builder = $this->modelsManager->createBuilder()
                                ->columns('u.iUserId,u.iSchoolId,t.iSubject,t.iCurGrade')
                                ->from(['u'=>'Admin\\Models\\user\\XhsysUser'])
                                ->leftJoin('Admin\\Models\\sys\\XhsysUserTch','t.iUserId=u.iUserId','t')
                                ->where('u.bDelete= 0  AND u.iUserId in ({ids:array})  ',['ids'=>$ids]);
                    $users = $builder->getQuery()->execute()->toArray();
                    $users = array_column($users,null,'iUserId');
                }

                $schools = XhschoolInfo::getSchoolSupportArray(true);
                $subject = XhsysEnum::getEnumByNodeName('学科');
                $grade   = XhsysEnum::getEnumByNodeName('年级');

                foreach ($result['userDTOList'] as $value) {
                    $user = $users[$value['userId']];
                    $data['rows'][] = array(
                        'id'         => $value['userId'],
                        'name'       => $value['userName'],
                        'logonName'  => $value['logonName'],
                        'createTime' => date('Y-m-d H:i', strtotime($value['createTime'])),
                        'schoolName' => isset($schools[$user['iSchoolId']]) ? $schools[$user['iSchoolId']] : '',
                        'subject'    => isset($subject[$user['iSubject']]) ? $subject[$user['iSubject']] : '',
                        'grade'      => isset($grade[$user['iCurGrade']]) ? $grade[$user['iCurGrade']] : ''
                    );
                }
            }
        } elseif ($dataType == 'out') {
            $schoolId = $this->request->getPost('schoolId', 'string');
            $subjectId = $this->request->getPost('subjectId', 'string');
            $schoolBase = new SchoolBase();
            $result = $schoolBase->getSchoolTeachers(array(), array('schoolId' => $schoolId));
            $ids = array();
            foreach ($result as $value) {
                $ids[] = $value['id'];
            }
            $result = $schoolBase->getBatchUserInfo($ids);
            if (!empty($result)) {
                if ($subjectId === '0') {
                    foreach ($result as $value) {
                        $subjectArr = array();
                        if (!empty($value['teacherAbilities'])) {
                            foreach ($value['teacherAbilities'] as $v) {
                                $subjectArr[$v['subject']] = $dictionariesArr['subject'][$v['subject']];
                            }
                        }
                        if (!empty($subjectArr)) {
                            ksort($subjectArr);
                            $subjectStr = implode(',', $subjectArr);
                            if (mb_strlen($subjectStr) <= 8) {
                                $subjectStr = mb_substr($subjectStr, 0, 8);
                            } else {
                                $subjectStr = mb_substr($subjectStr, 0, 8) . "...";
                            }
                        }
                        $data['rows'][] = array(
                            'id' => $value['id'],
                            'name' => $value['name'],
                            'logonName' => $value['logonName'],
                            'subject' => $subjectStr,
                            'updatedAt' => date('Y-m-d H:i', strtotime($value['updatedAt'])),
                        );
                    }
                    $data['total'] = count($data['rows']);
                } else {
                    foreach ($result as $value) {
                        $subjectArr = array();
                        if (!empty($value['teacherAbilities'])) {
                            foreach ($value['teacherAbilities'] as $v) {
                                $subjectArr[$v['subject']] = $dictionariesArr['subject'][$v['subject']];
                            }
                            if (!empty($subjectArr)) {
                                ksort($subjectArr);
                                $subjectStr = implode(',', $subjectArr);
                                if (mb_strlen($subjectStr) <= 8) {
                                    $subjectStr = mb_substr($subjectStr, 0, 8);
                                } else {
                                    $subjectStr = mb_substr($subjectStr, 0, 8) . "...";
                                }
                            }
                            if (in_array($subjectId, array_keys($subjectArr))) {
                                $data['rows'][] = array(
                                    'id' => $value['id'],
                                    'name' => $value['name'],
                                    'logonName' => $value['logonName'],
                                    'subject' => $subjectStr,
                                    'updatedAt' => date('Y-m-d H:i', strtotime($value['updatedAt'])),
                                );
                            }
                        }
                    }
                    $data['total'] = count($data['rows']);
                }
            }
        }
        return $this->response->setJsonContent($data);
    }

	/**
	 * 查看已关联学校情况页面
	 *
	 * @return array|\Phalcon\Mvc\View|string
	 *
	 * create by qgz 20180828
	 */
    public function showConnSchoolAction($returnArr=false,$bookId=''){
    	if (!$returnArr){//返回数据数组
		    $bookId = $this->request->getQuery('bookId');
		    $this->view->pick('res/showConnSchool');
		    if (!$bookId){
			    return $this->sendViewError('缺少参数');
		    }
	    }
	    $getArr = array(
		    'bookId' => $bookId,
		    'page' => 1,
		    'size' => 100000,
	    );
	    $questionPrivilege = new QuestionPrivilege();
	    $result = $questionPrivilege->getBookScopeUser($getArr);//接口获取教师列表
	    $school = $sortSchool = [];
	    $userNum = 0;
	    if(isset($result['userDTOList']) && count($result['userDTOList']) > 0 ){
		    Main::runUserSchoolId($result['userDTOList'], 'userId', 'schoolId');
	    }
	    foreach ($result['userDTOList'] as $value) {
		    $schoolId = $value['schoolId'];
		    if (isset($school[$schoolId])){
			    $school[$schoolId]['teaNum'] ++;
		    } else {
			    $school[$schoolId]['teaNum'] = 1;
		    }
		    $school[$schoolId]['iSchoolId'] = $schoolId;
		    XhschoolInfo::runSchoolName($school[$schoolId],false);
		    $userNum++;
	    }
	    if (empty($school)){
		    return $returnArr ? $school : $this->sendViewError('该书暂未绑定学校老师');
	    }
	    foreach ($school as $key => $item){
	    	if (in_array($key, $this->schoolSort)){//有几个学校展示总在前面
	    		$sortSchool[$key] = $item;
	    		unset($school[$key]);
		    }
	    }
	    if (!empty($sortSchool)){
		    $school = $sortSchool + $school;
	    }
	    if ($returnArr){
		    return $school;
	    }
	    $schoolNum = count($school);
	    return $this->view->setVars([
		    'data' => $school,
		    'schoolNum' => $schoolNum,
		    'userNum' => $userNum
	    ]);
    }

	/**
	 * 书本使用详情页
	 *
	 * @return \Phalcon\Mvc\View|string
	 *
	 * create by qgz 20180820
	 */
    public function showDetailInfoAction(){
	    $this->view->setTemplateBefore('listForm');
	    Assets::easyUI('js/res/showBookDetail.js');
	    $listButtonArr = $listSearchArr = [];
	    $listSearchArr[] = ['type' => 'text', 'id' => 'list_search_startTime', 'label' => '开始时间：'];
	    $listSearchArr[] = ['type' => 'text', 'id' => 'list_search_endTime', 'label' => '   结束时间：'];
	    return $this->view->setVars([
		    'List' => Template::createList('list', 'XHRes_ShowBookDetail', [
			    'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr)
		    ])
	    ]);
    }

	/**
	 * 获取书本使用详情数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180820
	 */
    public function getBookUseDetailAction(){
	    $page = $this->request->getPost('page');
	    $rows = $this->request->getPost('rows');
    	$bookId = $this->request->getPost('bookId');
        $schoolId = $this->request->getPost('schoolId');//教辅申请页选择的学校展示在前面
	    $startTime = $this->request->getPost('startTime');
	    $endTime = $this->request->getPost('endTime');
	    $return = ['total' => 0, 'rows' => []];
	    if (!$startTime && !$endTime){
    		return $this->sendJsonResponse($return);
	    }
	    if (!$bookId){
		    return $this->sendErrorResponse(400,'缺少书id');
	    }
	    $params = [
//	    	'schoolId' => 0,
//		    'bookId' => $bookId,
	    ];
    	if ($startTime){
		    $params['startTime'] = strtotime($startTime);
	    }
	    if ($endTime){
		    $params['endTime'] = strtotime($endTime);
	    }
	    try {
//		    $data = CloudTask::getBookUseDetail($params);
		    $data = CloudTask::getBookUseDetail(0, $bookId, $params);
		    if (empty($data)){
			    return $this->sendJsonResponse($return);
		    }
		    $return['total'] = count($data);//不分页了
//		    $rowsArr = array_chunk($data, $rows);
//		    $return['rows'] = $rowsArr[$page-1];
            $return['rows'] = $data;
		    Tool::runTimestamp($return['rows'], 'lastTime');
		    Main::runUserSchoolId($return['rows'], 'teacherId', 'schoolId');
		    Main::runSchoolNameByIdStr($return['rows'], ['schoolId' => 'schoolName'], true);
		    if ($schoolId) {//教辅申请页使用情况选择学校展示在前面
                $return['rows'] = $this->handleUseDetail($return['rows'], $schoolId);
                $return['total'] = count($return['rows']);
            }
		    return $this->sendJsonResponse($return);
	    } catch (\Exception $e) {
		    return $this->sendErrorResponse(json_encode($e->getMessage()));
	    }
    }

    /**
     * 处理获取有权限学校的使用情况
     *
     * @param $data
     * @param $schoolId
     *
     * @return array
     * @throws \Helpers\XhException
     *
     * create by qgz 20190226
     */
    public function handleUseDetail($data, $schoolId)
    {
        $return = [];
        if (!$data) {
            return $return;
        }
        $powerIds = School::getPower();
        if ($powerIds !== true) {
            if (!$powerIds) {
                return $return;
            }
            foreach ($data as $value) {
                if (!in_array($value['schoolId'], $powerIds)) {//展示有权限的学校
                    continue;
                }
                if ($schoolId && $value['schoolId'] == $schoolId) {
                    $value['schoolName'] = "<div style='background-color: green;color:white' title='该学校已有排期计划'>" . $value['schoolName'] . "</div>";
                    array_unshift($return, $value);//已申请学校在前面
                } else {
                    array_push($return, $value);
                }
            }
        }
        return array_values($return);
    }

    /**
     * 教师列表
     *
     * create by dale 20180329
     */
    public function rightTeacherListAction(){
        $this->view->pick('res/rightTeacherList');
        Assets::easyUI('js/res/rightTeacherList.js');
        Template::exists('XHRes_School', 'list') && Template::exists('XHRes_TeacherBookOut', 'list')
        or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106008));


        $schSearchArr[] = ['type'=>'text', 'id'=>'SchoolList_Search','style'=>'width:100px;','label'=>' '];
        $schSearchArr[] = ['type'=>'button', 'id'=>'bt_SchoolList_Search', 'text'=>'确定', 'icon'=>'fa-search', 'style'=>'margin-left:5px'];


        //teacherSelect
        $subject = XhsysEnum::getEnumByNodeName('学科');

        $subject[''] = '请选择';
        $grade     = XhsysEnum::getEnumByNodeName('年级');
        $grade[''] = '请选择';
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_subject', 'data' => $subject, 'default' =>'');
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_grade', 'data' => $grade, 'default' =>'');
        $tchSearchArr[] = ['type'=>'text', 'id'=>'TeacherList_Search', 'label'=>' ','style'=>'width:100px;'];
        $tchSearchArr[] = ['type'=>'button', 'id'=>'bt_TeacherList_Search', 'text'=>'确定', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];

        $this->view->setVars(array(
            'SchoolList'    => Template::createList('SchoolList', 'XHRes_School',array(
                'searchToolbar' =>  Template::createSearchToolBar($schSearchArr),
                'checkbox'      => false,
                'field'         => array('iSchoolId', 'sSchoolName'),
                'tableAttr'     => array(
                    'singleSelect'  => 'true'
                )
            )),
            'TeacherList'   => Template::createList('TeacherList','XHRes_TeacherBookOut', array(
                'searchToolbar' =>  Template::createSearchToolBar($tchSearchArr),
                'checkbox'      => true,
                'field'         => array('iUserId', 'sUserName', 'iUserSex', 'sLogonName', 'iCurGrade','iSubject','sSchoolName','iSchoolId'),
            ))
        ));
    }



    /**
     * 教师与书本关联和取消关联
     *
     * create by wy 20180201
     */
    public function contactTeacherAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $dataType = $this->request->getPost('type', 'string');
        $bookId = $this->request->getPost('bookId', 'string');
        $dbRollback = false;                //事务标识
        $this->db->begin();                 //事务开始
        if ($dataType == 'in') {
            $ids = explode(',', $this->request->getPost('ids'));
            $names = explode(',', $this->request->getPost('names'));
            $logonNames = explode(',', $this->request->getPost('logonNames'));
            $questionPrivilege = new QuestionPrivilege();
            foreach ($ids as $key => $value) {
                $getArr = array(
                    'bookId' => $bookId,
                    'logonName' => $logonNames[$key],
                    'powerType' => 2,
                    'userId' => $value,
                    'userName' => $names[$key],
                );
                $result = $questionPrivilege->setUserBookPowers($getArr);
                if ($result['code'] !== 200) {
                    $dbRollback = true;
                    goto dealTrans;
                }
            }
        } elseif ($dataType == 'out') {
            $ids = explode(',', $this->request->getPost('ids'));
            $questionPrivilege = new QuestionPrivilege();
            foreach ($ids as $value) {
                $userBookPowers = $questionPrivilege->getUserBookPowers(array(), array('userId' => $value));
                foreach ($userBookPowers as $v) {
                    if ($v['bookId'] == $bookId) {
                        $userBookPowerId = $v['userBookPowerId'];
                    }
                }
                $result = $questionPrivilege->deleteUserBookPowers(array(), array('userBookPowerId' => $userBookPowerId));
                if ($result['code'] !== 200) {
                    $dbRollback = true;
                    goto dealTrans;
                }
            }
        }
        dealTrans:
        if ($dbRollback) {
            $this->db->rollback();
            die(Main::showMessageModal('操作失败！', 109103012));
        }
        $this->db->commit();   //事务结束
        echo '操作成功！';
    }

    /**
     * 创建教辅申请
     *
     *
     * create by qgz 20180605
     */
    public function addReferenceApplyAction(){
        Assets::select2();
        Assets::easyUI('js/res/addReferenceApply.js');
        $this->view->pick('res/addReferenceForm');
        $data = $this->request->getQuery();
        $params = ['existData' => false, 'applyData' => '{}', 'iId' => '-1', 'modify' => 1, 'app' => json_encode('noApp')];
        if ($data['bookId'] && $data['bookName']){
            $params['existData'] = true; //教辅书Id是否存在
            $params['bookId'] = $data['bookId'];
            $params['bookName'] = $data['bookName'];
            $params['app'] = json_encode($this->appPageToAppCode[$data['app']]);
        }
        $this->view->setVars($params);
    }

    /**
     * 根据书id查询哪些应用在用这本书，不允许教辅申请的除外
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181113
     */
    public function getBookAppByIdAction()
    {
        $bookId = $this->request->getPost('bookId');
        if (!$bookId) {
            return $this->sendErrorResponse(400, '请输入书id');
        }
        $return = ['type' => 0, 'data' => []];
        $books = new Books();
        $checkIsApply = $books->getBookDetail(trim($bookId));
        if (!$checkIsApply) {
            return $this->sendJsonResponse($return);
        }
        if (!$checkIsApply['bookSecurity']) {//不允许教辅申请
            $return['type'] = 1;
            return $this->sendJsonResponse($return);
        }
        $questionPrivilege = new QuestionPrivilege();
        $appList = $questionPrivilege->getBookAppById($bookId);
        if (!$appList['packageNameList']) {
            return $this->sendJsonResponse($return);
        }
        $handleAppCode = $this->appPageToAppCode;
        $data = App::getAppNames();
        foreach ($data as $key => $item) {
            if (in_array($key, $appList['packageNameList']) && isset($handleAppCode[$key])) {
                $return['data'][] = ['id' => $handleAppCode[$key], 'text' => $item];
            }
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 获取所有应用列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by qgz 20181113
     */
    public function getAllAppAction()
    {
        $return[] = [];
        $data = App::getAppCodes();
        if ($data){
            foreach ($data as $key => $value){
                $return[] = ['id' => $key, 'text' => $value];
            }
        }
        return $this->sendJsonResponse($return);
    }

	/**
	 * 双击教辅申请编辑页
	 *
	 * @return \Phalcon\Mvc\View
	 *
	 * create by qgz 20180827
	 */
    public function showModifyRefApplyAction(){
	    $id = $this->request->getQuery('id');
        Assets::easyUI('js/res/refApplyDetail.js');
	    $this->view->pick('res/refApplyDetail');
	    return $this->view->setVars(['id' => $id]);
    }

	/**
	 * 教辅申请老师学校统计页面
	 *
	 * @return \Phalcon\Mvc\View|string
	 *
	 * create by qgz 20180827
	 */
    public function statTeaAndSchFormAction(){
	    $postData = $this->request->getQuery();
	    $this->view->pick('res/showStatTeaAndSchForm');
	    Assets::easyUI('js/res/showStatTeaAndSchForm.js');
	    $teaDataArr = $schoolData = [];
	    $schoolNum = 0;
	    $type = 1;
	    if (!$postData['id']){
		    return $this->sendViewError('缺少教辅申请id');
	    }
	    $data = XhresReferenceApply::findFirst(['columns' => 'iBookId, sTeacherList', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
	    if (!$data){
		    return $this->sendViewError('缺少教辅申请数据');
	    }
	    $data = $data->toArray();
	    if (!$data['iBookId']){
	    	$type = 2;
	    }
	    $bookId = $data['iBookId'];
	    if ($data['sTeacherList']){
		    $data = explode(',', $data['sTeacherList']);
		    $userInfo = XhsysUser::getUserNameById($data);
		    foreach ($data as $value){
			    $params = array(
				    'page' => 1,
				    'size' => 10000,
				    'userId' => $value,
				    'publishStatus' => 0,
			    );
			    $books = new Books();
			    $userBookPowers = $books->getAllBookList($params);//统计老师名下书本情况
			    $teaInfo['teaName'] = isset($userInfo[$value]) ? $userInfo[$value] : '[无姓名]';
			    $teaInfo['teaNum'] = $userBookPowers['totalCount'];
			    $teaInfo['bookDetail'] = [];
			    if ($userBookPowers && count($userBookPowers['bookClientDTOList']) != 0){
				    $teaInfo['bookDetail'] = $this->handleBookDetail($value, $userBookPowers['bookClientDTOList']);
			    }
			    $teaInfo['rowSpan'] = 0;//计算rowSpan值
			    foreach ($teaInfo['bookDetail'] as $item){
				    $teaInfo['rowSpan'] += $item['rowSpan'];
			    }
			    $teaDataArr[] = $teaInfo;
			    unset($books,$teaInfo);
		    }
	    }
	    $teaDataArr = $this->handleFinaData($teaDataArr);
	    if ($type == 1){//有bookId时
		    $schoolData = $this->showConnSchoolAction(true,$bookId);//统计学校数量
	    }
	    if ($schoolData){
		    $schoolNum = count($schoolData);
	    }
	    return $this->view->setVars([
	    	'type' => $type,
		    'data' => $teaDataArr,
		    'schoolNum' => $schoolNum,
		    'schoolData' => $schoolData
	    ]);
    }

	/**
	 * 处理成列数据返回前端
	 *
	 * @return array
	 *
	 * create by qgz 20180830
	 */
    public function handleFinaData($data){
	    $handArr = [];
    	if (!$data){
		    return $handArr;
	    }
    	foreach ($data as $key => $dataArr){
    		if (empty($dataArr['bookDetail'])){
			    $handArr[] = [
				    'teaName' => $dataArr['teaName'],
				    'teaNum' => 0,
				    'bookType' => '',
				    'gradeId' => '',
				    'grade' => '',
				    'gradeNum' => 0,
				    'teaRowSpan' => 1,
				    'bookRowSpan' => 1,
				    'isTeaFirstRow' => 1,
				    'isBookRowSpan' => 1,
			    ];
		    } else {
			    foreach ($dataArr['bookDetail'] as $key1 => $value){
				    foreach ($value['gradeDetail'] as $key2 => $item){
					    $handArr[] = [
						    'teaName' => $dataArr['teaName'],
						    'teaNum' => $dataArr['teaNum'],
						    'bookType' => $value['bookType'],
						    'gradeId' => $item['gradeId'],
						    'grade' => $item['grade'],
						    'gradeNum' => $item['gradeNum'] ? $item['gradeNum'] : 0,//数量
						    'teaRowSpan' => $key1 == 0 && $key2 == 0 ? $dataArr['rowSpan'] : 1,//老师列的rowspan值
						    'bookRowSpan' => $key2 == 0 ? $value['rowSpan'] : 1,//书本类型列的rowspan值
						    'isTeaFirstRow' => $key1 == 0 && $key2 == 0 ? 1 : 0,//是否老师列下的第一行
						    'isBookRowSpan' => $key2 == 0 ? 1 : 0,//是否书本类型列下的第一行
					    ];
				    }
			    }
		    }
	    }
	    return $handArr;
    }

	/**
	 * 处理统计书详细-书类型数据
	 *
	 * @return array
	 *
	 * create by qgz 20180829
	 */
    public function handleBookDetail($userId, $dataList){
    	$return = [];
	    if (empty($dataList)){
		    return $return;
	    }
	    $typeArr = $back = $fina = $last = [];
	    foreach ($dataList as $value){
	    	$typeArr[$value['libraryType']][] = $value;
	    }
	    foreach ($typeArr as $key => $item){
	    	if ($key == 1 || $key == 8){//同步书、专题书 统计书详情
			    $fina[$key] = $this->handleTeachDetail($userId, $key, $item);
		    } else {
			    $fina[$key][] = ['gradeId' => '', 'grade' => '', 'gradeNum' => count($item)];
		    }
	    }
	    $bookType = $this->runLibraryType();
	    foreach ($fina as $key => $value){
	    	$back['bookType'] = $bookType[$key];
	    	$back['gradeDetail'] = $value;
	    	$back['rowSpan'] = count($value);
	    	$last[] = $back;
	    }
	    return $last;
    }

	/**
	 * 处理统计书详细-书年级数据
	 *
	 * @return array
	 *
	 * create by qgz 20180829
	 */
	public function handleTeachDetail($userId,$libraryType, $dataList){
		$fina = $return = [];
		if (empty($dataList)){
			return $fina;
		}
		$enum = $this->getEnumTypeList();//年级、科目、学科枚举
		foreach ($dataList as $value){
			if (!isset($fina[$value['gradeId']])){
				$fina[$value['gradeId']] = 1;
			} else {
				$fina[$value['gradeId']]++;
			}
		}
		if ($fina){
			foreach ($fina as $key => $item){
				if (!isset($enum['grade'][$key])){
					$return[] = ['gradeId' => $userId . '_' . $libraryType . '_' . $key, 'grade' => '[不属于任何年级]', 'gradeNum' => $item];
				} else {
					$return[] = ['gradeId' => $userId . '_' . $libraryType . '_' . $key, 'grade' => $enum['grade'][$key], 'gradeNum' => $item];
				}
			}
		}
		return $return;
	}

	/**
	 * 展示具体书id-name信息
	 *
	 * @return \Phalcon\Mvc\View|string
	 *
	 * create by qgz 20180829
	 */
	public function getBookByGradeAction(){
		$id = $this->request->getQuery('id');
		if (!$id){
			return $this->sendViewError('缺少id');
		}
		$id = explode('_', $id);//32233_1_71 组和id，老师id+书类型+年级id
		if (count($id) != 3 || $id[0] == 0 || $id[1] == 0|| $id[2] == 0){
			return $this->sendViewError('查询组合id不正确');
		}
		$params = array(
			'page' => 1,
			'size' => 10000,
			'userId' => $id[0],
			'publishStatus' => 0,
		);
		$data = [];
		$books = new Books();
		$userBookPowers = $books->getAllBookList($params);//统计老师名下书本情况
		if ($userBookPowers && count($userBookPowers['bookClientDTOList']) != 0){
			foreach ($userBookPowers['bookClientDTOList'] as $value){
				if ($value['libraryType'] == $id[1] && $value['gradeId'] == $id[2]){
					$data[] = [
						'bookId' => $value['bookId'],
						'bookName' => $value['bookName']
					];
				}
			}
		}
		$this->view->pick('res/showBookDetail');
		return $this->view->setVars([
			'data' => $data
		]);
	}
    /**
     * 修改申请人信息
     *
     * @return mixed
     *
     * create by qgz 20180608
     */
    public function modifyReferenceApplyAction(){
        if (!UserPower::checkUserPower('Res_ReferenceApply_Edit')) {
            return $this->sendViewError('对不起，您没有操作权限');
        }
        Assets::select2();
        Assets::easyUI('js/res/addReferenceApply.js');
        $this->view->pick('res/addReferenceForm');
        $postData = $this->request->getQuery();
        if (!$postData['id']){
            return $this->sendViewError('请选择后操作');
        }
        $data = XhresReferenceApply::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
        if (!$data){
            return $this->sendViewError('暂无数据');
        }
        $data = $data->toArray();
        $data['sTeacherList'] = explode(',', $data['sTeacherList']);
        $params = ['modify' => 2, 'existData' => false];
        $params['applyData'] = json_encode($data);
        $params['applyDataArr'] = $data;
        $params['iId'] = $postData['id'];
        $params['app'] = json_encode('noApp');
        $this->view->setVars($params);
    }

    /**
     * 获取所有选项数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by qgz 20180607
     */
    public function getReferAllSelectDataAction(){
    	$type = $this->request->getPost('type');
	    $id = $this->request->getPost('id');
        $return = ['school' => [], 'app' => [], 'class' => [], 'subject' => [], 'teaList' => [], 'allTeaList' => []];
        //学校
        $parameters = [
            'columns'    => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete = 0 AND (iStatus = 1 OR iStatus = 2) '
        ];
        $data = XhschoolInfo::find($parameters)->toArray();
        if ($data){
            foreach ($data as $value){
                $return['school'][] = ['id' => $value['iSchoolId'], 'text' => $value['sSchoolName']];
            }
        }else{
            return $this->sendErrorResponse(500, '暂无学校数据');
        }
        //应用
        $data = App::getAppCodes();
        if ($data){
            foreach ($data as $key => $value){
                $return['app'][] = ['id' => $key, 'text' => $value];
            }
        }else{
            return $this->sendErrorResponse(500, '暂无应用数据');
        }
        //年级
        $data = XhsysEnum::getEnumByNodeName('年级');
        if ($data){
            foreach ($data as $key => $value){
                $return['class'][] = ['id' => $key, 'text' => $value];
            }
        }else{
            return $this->sendErrorResponse(500, '暂无年级数据');
        }
        //科目
        $data = XhsysEnum::getEnumByNodeName('学科');
        if ($data){
            foreach ($data as $key => $value){
                if ($value != '文综') {
                    $return['subject'][] = ['id' => $key, 'text' => $value];
                }
            }
        }else{
            return $this->sendErrorResponse(500, '暂无学科数据');
        }
        if ($type == 2 || $type == 3){//修改返回教师列表
	        $parameter = ['columns' => 'sTeacherList, iSchoolId, iSubject', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $id]];
	        if ($type == 2){
		        $teaList = XhresReferenceApply::findFirst($parameter);
	        } else {
		        $teaList = XhresReferenceRepeal::findFirst($parameter);
	        }
        	if ($teaList){
		        $teaList = $teaList->toArray();
		        $teachStr = '';
		        if ($teaList['sTeacherList']){
			        $return['teaList'] = explode(',', $teaList['sTeacherList']);
                    $teachStr = $teaList['sTeacherList'];
		        }
		        if ($teaList['iSchoolId'] && $teaList['iSubject']){
			        $sql = "SELECT iUserId, sUserName FROM XHSys_User WHERE ( iSchoolId = {$teaList['iSchoolId']} AND bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND iUserType = 4 AND iUserId IN ( 
							SELECT iUserId FROM XHSys_UserTch WHERE bDelete = 0  AND iSubject = {$teaList['iSubject']} ) ) ";
			        if ($teachStr) {//将全部老师id加到下拉列表
			            $sql .= " OR (iUserId IN ({$teachStr})) ";
                    }
			        $data = $this->db->fetchAll($sql);
			        if ($data){
				        foreach ($data as $value){
					        $return['allTeaList'][] = ['id' => $value['iUserId'], 'text' => $value['sUserName']];
				        }
			        }
		        }
	        }
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 获取教师数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180606
     * modify by qgz 20180620 配置某些学校下的科目可以不必选老师
     */
    public function getTeacherDataAction(){
        $schoolId = $this->request->getPost('schoolId');
        $subjectId = $this->request->getPost('subjectId');
	    $checkType = $this->request->getPost('checkType');
        $return = ['data' => [], 'checkTeacher' => true];
        if (!$schoolId || !$subjectId){
            return $this->sendJsonResponse($return);
        }

        $checkTeacherArr = Main::getConfigByName('bookApplyNoTch');
        $subjectNameArr = [];
        if (!empty($checkTeacherArr) && isset($checkTeacherArr[$schoolId])){
            if (empty($checkTeacherArr[$schoolId])){
                $return['checkTeacher'] = false;//全部不检查
            } else {
                $subjectNameArr = explode(',', str_replace('，', ',', $checkTeacherArr[$schoolId]));
            }
        }
        if (!empty($subjectNameArr)){
            $allSubject = XhsysEnum::getEnumByNodeName('学科');
            if (in_array($allSubject[$subjectId], $subjectNameArr)){
                $return['checkTeacher'] = false;//不检查
            }
        }

        $sql = "SELECT iUserId, sUserName FROM XHSys_User WHERE iSchoolId = $schoolId AND bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND iUserType = 4 AND iUserId IN ( 
                SELECT iUserId FROM XHSys_UserTch WHERE bDelete = 0  AND iSubject = $subjectId )";
        $data = $this->db->fetchAll($sql);
        if ($data){
            foreach ($data as $key => $value){
                $return['data'][] = ['id' => $value['iUserId'], 'text' => $value['sUserName']];
            }
        } else {
            if ($return['checkTeacher'] == true && $checkType != 'true'){
                return $this->sendErrorResponse(500, '所选学校和科目下的教师数据为空');
            }
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 教辅申请--老师申请情况统计
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20190214
     */
    public function teaStatAction()
    {
        $this->view->pick('res/teaStatForm');
        Assets::select2();
        Assets::easyUI('js/res/teaStatForm.js');
        return $this->view->setVars([]);
    }

    /**
     * 获取教辅申请老师统计数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by qgz 20190215
     */
    public function getTeaStatDataAction()
    {
        $school = $this->request->getPost('school');
        $teaDataArr = $allTeaArr = $fina = $numArr = [];
        $params = [
            'columns' => 'iSchoolId, iClassId, iSubject, sTeacherList',
            'conditions' => "bDelete = 0 and iClassId != '' and iClassId is not null and iSubject != '' and iSubject is not null "
        ];
        if ($school) {
            $params['conditions'] .= " and iSchoolId = {$school} ";
        } else {
            $params['conditions'] .= " and iSchoolId != '' and iSchoolId is not null ";
        }
        $data = XhresReferenceApply::find($params)->toArray();
        if (!$data) {
            return $this->sendJsonResponse($fina);
        }
        $handleArr = [];
        foreach ($data as $handleValue) {
            if ($handleValue['sTeacherList']) {
                $handleArr = array_values(array_filter(array_unique(array_merge($handleArr, explode(',', $handleValue['sTeacherList'])))));
            }
        }
        if (!$handleArr) {
            return $this->sendJsonResponse($fina);
        }
        //获取已申请的老师数据
        $tchIds = implode(",", $handleArr);
        $sql = "
SELECT a.iUserId, a.iSubject, a.iCurGrade, b.iSchoolId
FROM
	XHSys_UserTch a
LEFT JOIN XHSys_User b ON a.iUserId = b.iUserId
WHERE
	a.iSubject IS not NULL AND a.iSubject != '' AND a.iCurGrade IS not NULL AND a.iCurGrade != '' AND
	a.iUserId IN ({$tchIds})";
        $findTeaData = $this->db->fetchAll($sql);
        if (!$findTeaData) {
            return $this->sendJsonResponse($fina);
        }
        foreach ($findTeaData as $key => $value) {
            $teaDataArr[$value['iSchoolId']][$value['iSubject']][$value['iCurGrade']][] = $value['iUserId'];
            unset($findTeaData[$key]);
        }
//        foreach ($data as $key => $value) {
//            $teachArr = [];
//            if ($value['sTeacherList']) {
//                $teachArr = array_values(array_filter(array_unique(explode(',', $value['sTeacherList']))));
//            }
//            if (!isset($teaDataArr[$value['iSchoolId']][$value['iSubject']][$value['iClassId']])) {
//                $teaDataArr[$value['iSchoolId']][$value['iSubject']][$value['iClassId']] = $teachArr;
//            } else {
//                $teaDataArr[$value['iSchoolId']][$value['iSubject']][$value['iClassId']] = array_values(array_filter(array_unique(array_merge($teaDataArr[$value['iSchoolId']][$value['iSubject']][$value['iClassId']], $teachArr))));
//            }
//            unset($data[$key]);
//        }
        unset($key, $value);
//        $teaDataArr = [1=>123, 2747=>5];

        //获取学校下科目年级老师总数量
        $schoolIds = implode(",", array_keys($teaDataArr));
        $sql = "
SELECT a.iUserId, a.iSubject, a.iCurGrade, b.iSchoolId
FROM
	XHSys_UserTch a
LEFT JOIN XHSys_User b ON a.iUserId = b.iUserId
WHERE
	a.iSubject IS not NULL AND a.iSubject != '' AND a.iCurGrade IS not NULL AND a.iCurGrade != '' AND
	a.iUserId IN (
		SELECT
			iUserId
		FROM
			XHSys_User
		WHERE
			iSchoolId IN ({$schoolIds})
	)";
        $allTeaData = $this->db->fetchAll($sql);
        if (!$allTeaData) {
            return $this->sendJsonResponse($fina);
        }
        foreach ($allTeaData as $key => $value) {
            if (!isset($allTeaArr[$value['iSchoolId']][$value['iSubject']][$value['iCurGrade']])) {
                $allTeaArr[$value['iSchoolId']][$value['iSubject']][$value['iCurGrade']]['user'][] = $value['iUserId'];
                $allTeaArr[$value['iSchoolId']][$value['iSubject']][$value['iCurGrade']]['num'] = 1;
            } else {
                if (!in_array($value['iUserId'], $allTeaArr[$value['iSchoolId']][$value['iSubject']][$value['iCurGrade']]['user'])) {
                    $allTeaArr[$value['iSchoolId']][$value['iSubject']][$value['iCurGrade']]['user'][] = $value['iUserId'];
                    $allTeaArr[$value['iSchoolId']][$value['iSubject']][$value['iCurGrade']]['num']++;
                }
            }
        }
        unset($allTeaData);
        foreach ($teaDataArr as $schoolId => $value) {
            foreach ($value as $subject => $item) {
                foreach ($item as $class => $info) {
                    $detail = [
                        'iSchoolId' => $schoolId,
                        'subject' => $subject,
                        'class' => $class,
                        'done' => count($info)
                    ];
                    if (isset($allTeaArr[$schoolId][$subject][$class])) {
                        $detail['all'] = $allTeaArr[$schoolId][$subject][$class]['num'];
                        $detail['noDone'] = $allTeaArr[$schoolId][$subject][$class]['num'] - count($info);
                    } else {
                        $detail['all'] = 0;
                        $detail['noDone'] = 0;
                    }
                    $fina[] = $detail;
                    //计算rowSpan值
                    if (isset($numArr[$schoolId]['school'])) {
                        $numArr[$schoolId]['school'] ++;
                    } else {
                        $numArr[$schoolId]['school'] = 1;
                    }
                    if (isset($numArr[$schoolId]['subject'][$subject])) {
                        $numArr[$schoolId]['subject'][$subject] ++;
                    } else {
                        $numArr[$schoolId]['subject'][$subject] = 1;
                    }
                }
            }
        }
        XhschoolInfo::runSchoolName($fina);
        $enum['iClassId'] = XhsysEnum::getEnumByNodeName('年级');
        $enum['iSubject'] = XhsysEnum::getEnumByNodeName('学科');
        $firstSchool = $firstClass = [];
        foreach ($fina as &$value) {
            if (!in_array($value['iSchoolId'], $firstSchool)) {
                $value['firstSchRow'] = 1;
                $value['schoolRowSpan'] = isset($numArr[$value['iSchoolId']]['school']) ? $numArr[$value['iSchoolId']]['school'] : 1;
                $firstSchool[] = $value['iSchoolId'];
            } else {
                $value['firstSchRow'] = 0;
                $value['schoolRowSpan'] = 1;
            }
            if (!in_array($value['iSchoolId'] . '_' . $value['subject'], $firstClass)) {
                $value['firstSubRow'] = 1;
                $value['subjectRowSpan'] = isset($numArr[$value['iSchoolId']]['subject'][$value['subject']]) ? $numArr[$value['iSchoolId']]['subject'][$value['subject']] : 1;
                $firstClass[] = $value['iSchoolId'] . '_' . $value['subject'];
            } else {
                $value['firstSubRow'] = 0;
                $value['subjectRowSpan'] = 1;
            }
            $value['className'] = $enum['iClassId'][$value['class']];
            $value['subjectName'] = $enum['iSubject'][$value['subject']];
            $value['showId'] = $value['iSchoolId'] . '_' . $value['subject'] . '_' . $value['class'];//点击查看详情时的拼接id
            $value['showName'] = $value['sSchoolName'] . '_' . $value['subjectName'] . '_' . $value['className'];//点击查看详情时的拼接name
        }
        return $this->sendJsonResponse($fina);
    }

    /**
     * 获取所有学校列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190215
     */
    public function getAllSchoolDataAction()
    {
        $return[] = ['id' => '', 'text' => ''];
        $data = XhschoolInfo::getSchoolSupportArray();
        if ($data) {
            foreach ($data as $key => $value) {
                $return[] = ['id' => $key, 'text' => $value];
            }
            return $this->sendJsonResponse($return);
        } else {
            return $this->sendErrorResponse(500, '暂无学校数据');
        }
    }

    /**
     * 获取未申请老师数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190214
     */
    public function getOutApplyTeaAction()
    {
        $id = $this->request->getPost('teachApplyId');
        if (!$id) {
            return $this->sendErrorResponse(400, '组和id参数不正确');
        }
        $idArr = explode('_', $id);
        if (count($idArr) !== 3) {
            return $this->sendErrorResponse(400, '参数个数不正确');
        }
        $existArr = [];
        $data = XhresReferenceApply::find([
            'columns' => 'sTeacherList',
            'conditions' => "bDelete = 0 and iSchoolId = :iSchoolId: and iSubject = :iSubject: ",
            'bind' => ['iSchoolId' => $idArr[0], 'iSubject' => $idArr[1]]
        ])->toArray();
        if ($data) {
            foreach ($data as $value) {
                $existArr = array_values(array_unique(array_filter(array_merge($existArr, explode(',', $value['sTeacherList'])))));
            }
        }

        //所有年级科目老师数据
        $sql = "
SELECT a.iUserId
FROM
	XHSys_UserTch a
LEFT JOIN XHSys_User b ON a.iUserId = b.iUserId
WHERE
	a.iSubject = {$idArr[1]} AND a.iCurGrade = {$idArr[2]} AND
	a.iUserId IN (
		SELECT
			iUserId
		FROM
			XHSys_User
		WHERE
			iSchoolId = {$idArr[0]}
	)";
        $allTeaData = $this->db->fetchAll($sql);
        if (!$allTeaData) {
            return $this->sendSuccessResponse('无');
        }
        $allTeaData = array_values(array_unique(array_filter(array_diff(array_column($allTeaData, 'iUserId'), $existArr))));
        if (!$allTeaData) {
            return $this->sendSuccessResponse('无');
        }
        foreach ($allTeaData as $datum) {
            $teaData[] = ['iUserId' => $datum];
        }
        Main::runUserName($teaData,['iUserId' => 'userName']);
        $fina = [];
        foreach ($teaData as $datum) {
            $fina[] = $datum['userName'];
        }
        $msg = implode('、', $fina);
        return $this->sendSuccessResponse($msg);
    }

	/**
	 * 修改撤销教辅申请页
	 *
	 * @return string
	 *
	 * create by qgz 20180709
	 */
	public function modifyReferenceRepealAction(){
		if (!Power::exist('Res_ReferenceRepeal_Edit')) {
			return $this->sendViewError('对不起，您没有操作权限');
		}
		Assets::select2();
		Assets::easyUI('js/res/backReferenceApply.js');
		$this->view->pick('res/referenceRepealForm');
		$postData = $this->request->getQuery();
		if (!$postData['id']){
			return $this->sendViewError('请选择后操作');
		}
		$data = XhresReferenceRepeal::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
		if (!$data){
			return $this->sendViewError('暂无数据');
		}
		$data = $data->toArray();
		$data['sTeacherList'] = explode(',', $data['sTeacherList']);
		$params = ['modify' => 2, 'existData' => false];
		$params['applyData'] = json_encode($data);
		$params['applyDataArr'] = $data;
		$params['id'] = $postData['id'];
		$this->view->setVars($params);
	}

    /**
     * 保存教辅申请信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180606
     * modify by qgz 20181011 创建申请时记录是否有排期计划
     * modify by qgz 20181219 去掉是否有排期计划字段，取时直接计算
     */
    public function saveReferenceApplyAction()
    {
        $data = $this->request->getPost();
        $checkBookTeach = $this->checkBookTeacher($data);
        if (!$checkBookTeach) {
            return $this->sendErrorResponse(400, '所选老师在该学校和该书下已全部存在申请，请重新填写');
        }
//        $existPlan = 0;
        $bookSubject = $bookClass = $complete = $bookType = '';
        if ($data['haveId'] == 2 && $data['referenceId']) {//有书id检查iExistPlan是否已经有排期计划，记录入库（废弃，换为取数据时直接计算）
//            $findData = XhresReferenceApply::findFirst([
//                'conditions' => 'bDelete = 0 and iExistPlan in (1,2) and iBookId = :iBookId:',
//                'bind' => ['iBookId' => trim($data['referenceId'])]
//            ]);
//            if ($findData) {
//                $existPlan = $findData->iExistPlan;
//            }
            //增加学科版本信息
            $books = new Books();
            $result = $books->getBookDetail(trim($data['referenceId']));
            if ($result && $result['bookId'] == trim($data['referenceId'])) {
                $bookSubject = $result['subjectId'];
                $bookClass = $result['gradeId'];
                $complete = $result['bookComplete'];
                $bookType = $result['bookType'];
            }
        }
        $XhresReferenceApply = new XhresReferenceApply();
        $XhresReferenceApply->iStatus = 0;
//        $XhresReferenceApply->iExistPlan = $existPlan;
        $XhresReferenceApply->iSchoolId = trim($data['school']);
        $XhresReferenceApply->sAppCode = trim($data['application']);
        $XhresReferenceApply->iClassId = trim($data['grade']);
        $XhresReferenceApply->iSubject = trim($data['subject']);
        $XhresReferenceApply->bExistBookId = ($data['haveId'] == 2) ? 1 : 0;
        $XhresReferenceApply->iBookId = trim($data['referenceId']);
        $XhresReferenceApply->sBookName = trim($data['bookName']);
        $XhresReferenceApply->sTeacherList = !empty($data['teacher']) ? implode(',', $data['teacher']) : '';
        $XhresReferenceApply->iTeacherNum = !empty($data['teacher']) ? count($data['teacher']) : null;
        $XhresReferenceApply->bPaperBook = (isset($data['isPaper']) && $data['isPaper'] == 2) ? 1 : 0;
        $XhresReferenceApply->iReferenceNum = (isset($data['bookNum'])) ? $data['bookNum'] : null;
        $XhresReferenceApply->bElectronic = (isset($data['electronic']) && $data['electronic'] == 2) ? 1 : 0;
        $XhresReferenceApply->sBuyUrl = (isset($data['buyUrl'])) ? $data['buyUrl'] : null;
        $XhresReferenceApply->sTypeIn = (isset($data['typeIn'])) ? $data['typeIn'] : '';
        $XhresReferenceApply->sProgress = (isset($data['progress'])) ? $data['progress'] : '';
        $XhresReferenceApply->sTeachProgress = (isset($data['teachProgress'])) ? $data['teachProgress'] : '';
        $XhresReferenceApply->iVolumeId = $data['volume'];
        $XhresReferenceApply->sRemark = $data['remark'];
        if ($bookSubject !== '') {
            $XhresReferenceApply->iBookSubject = $bookSubject;
        }
        if ($bookClass !== '') {
            $XhresReferenceApply->iBookClass = $bookClass;
        }
        if ($complete !== '') {
            $XhresReferenceApply->iCompleteStatus = $complete;
        }
        if ($bookType !== '') {
            $XhresReferenceApply->iBookType = $bookType;
        }
        if (!$XhresReferenceApply->save()) {
            return $this->sendErrorResponse(500, '保存失败', $XhresReferenceApply->getError());
        } else {
            return $this->sendSuccessResponse('成功');
        }
    }

    /**
     * 检查是否  同一学校同一书本同一老师只能申请一次
     *
     * @param $data
     *
     * @return bool
     *
     * create by qgz 20181121
     */
    public function checkBookTeacher($data)
    {
        if (!isset($data['school']) || !isset($data['referenceId']) || !isset($data['teacher'])) {
            return true;
        }
        if (!$data['school'] || !$data['referenceId'] || !$data['teacher']) {
            return true;
        }
        $existData = XhresReferenceApply::find([
            'columns' => 'sTeacherList',
            'conditions' => " bDelete = 0 and sTeacherList is not null and sTeacherList != '' and iSchoolId = :iSchoolId: and iBookId = :iBookId: ",
            'bind' => ['iSchoolId' => $data['school'], 'iBookId' => $data['referenceId']]
        ])->toArray();
        if (!$existData) {
            return true;
        }
        $addTeaList = array_unique(array_filter($data['teacher']));
        $existData = array_unique(array_filter(explode(',', implode(',', array_column($existData, 'sTeacherList')))));
        if ($existData) {
            $isExist = array_diff($addTeaList, $existData);
            if (!$isExist) {//全部已在申请中，不让申请
                return false;
            }
        }
        return true;
    }

    /**
     * 根据书名模糊查询书id
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180928
     */
    public function bookIdsByNameKeyAction()
    {
        $key = $this->request->get('key');
        if (!$key) {
            return $this->sendJsonResponse([]);
        }
        $getArr = array(
            'page' => 1,
            'size' => 10000,
            'userId' => 0,
            'publishStatus' => 0,
            'bookName' => trim($key),
        );
        $return = [];
        $books = new Books();
        $result = $books->getAllBookList($getArr);
        if ($result && isset($result['bookClientDTOList']) && $result['bookClientDTOList']) {
            $return[] = ['id' => '', 'text' => '--请选择--'];
            foreach ($result['bookClientDTOList'] as $value) {
                if ($value['bookId']) {
                    $return[] = ['id' => $value['bookId'], 'text' => $value['bookName']];
                }
            }
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 保存修改教辅申请数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180608
     */
    public function saveModifyReferApplyAction(){
        $data = $this->request->getPost();
        if ($data['iId'] && $data['iId'] < 0){
            return $this->sendErrorResponse(400, '缺少ID，修改失败');
        }
        $XhresReferenceApply = XhresReferenceApply::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $data['iId']]]);
        if (!$XhresReferenceApply){
            return $this->sendErrorResponse(500, '找不到数据');
        }
        if (User::getId() == $XhresReferenceApply->iCreateUserId && ($XhresReferenceApply->iStatus == 3 || $XhresReferenceApply->iStatus == 1)){
            $XhresReferenceApply->iStatus = 0;
        }

//        $existPlan = 0;
        $bookSubject = $bookClass = $complete = $bookType = '';
        if (trim($data['referenceId'])) {//有书id检查iExistPlan是否已经有排期计划，记录入库（废弃，换为取数据时直接计算）
//            $findData = XhresReferenceApply::findFirst([
//                'conditions' => 'bDelete = 0 and iExistPlan in (1,2) and iBookId = :iBookId:',
//                'bind' => ['iBookId' => trim($data['referenceId'])]
//            ]);
//            if ($findData) {
//                $existPlan = $findData->iExistPlan;
//            }
            //增加学科版本信息
            $books = new Books();
            $result = $books->getBookDetail(trim($data['referenceId']));
            if ($result && $result['bookId'] == trim($data['referenceId'])) {
                $bookSubject = $result['subjectId'];
                $bookClass = $result['gradeId'];
                $complete = $result['bookComplete'];
                $bookType = $result['bookType'];
            }
        }
//        $XhresReferenceApply->iExistPlan = $existPlan;
        $XhresReferenceApply->iSchoolId = trim($data['school']);
        $XhresReferenceApply->sAppCode = trim($data['application']);
        $XhresReferenceApply->iClassId = trim($data['grade']);
        $XhresReferenceApply->iSubject = trim($data['subject']);
        $XhresReferenceApply->bExistBookId = ($data['haveId'] == 2) ? 1 : 0;
        $XhresReferenceApply->iBookId = trim($data['referenceId']);
        $XhresReferenceApply->sBookName = trim($data['bookName']);
        $XhresReferenceApply->sTeacherList = !empty($data['teacher']) ? implode(',', $data['teacher']) : '';
        $XhresReferenceApply->iTeacherNum = !empty($data['teacher']) ? count($data['teacher']) : null;
        $XhresReferenceApply->bPaperBook = (isset($data['isPaper']) && $data['isPaper'] == 2) ? 1 : 0;
        $XhresReferenceApply->iReferenceNum = (isset($data['bookNum'])) ? $data['bookNum'] : null;
        $XhresReferenceApply->bElectronic = (isset($data['electronic']) && $data['electronic'] == 2) ? 1 : 0;
        $XhresReferenceApply->sBuyUrl = (isset($data['buyUrl'])) ? $data['buyUrl'] : null;
        $XhresReferenceApply->sTypeIn = (isset($data['typeIn'])) ? $data['typeIn'] : '';
        $XhresReferenceApply->sProgress = (isset($data['progress'])) ? $data['progress'] : '';
        $XhresReferenceApply->sTeachProgress = (isset($data['teachProgress'])) ? $data['teachProgress'] : '';
        $XhresReferenceApply->iVolumeId = $data['volume'];
        $XhresReferenceApply->sRemark = $data['remark'];
        if ($bookSubject !== '') {
            $XhresReferenceApply->iBookSubject = $bookSubject;
        }
        if ($bookClass !== '') {
            $XhresReferenceApply->iBookClass = $bookClass;
        }
        if ($complete !== '') {
            $XhresReferenceApply->iCompleteStatus = $complete;
        }
        if ($bookType !== '') {
            $XhresReferenceApply->iBookType = $bookType;
        }
        if (!$XhresReferenceApply->save()){
            return $this->sendErrorResponse(500, '修改失败', $XhresReferenceApply->getError());
        }else{
            return $this->sendSuccessResponse('修改成功');
        }
    }

	/**
	 * 撤销教辅申请页
	 *
	 *
	 * create by qgz 20180709
	 */
	public function backReferenceApplyAction(){
		Assets::select2();
		Assets::easyUI('js/res/backReferenceApply.js');
		$this->view->pick('res/referenceRepealForm');
		$data = $this->request->getQuery();
		$params = ['applyData' => '{}', 'id' => '-1', 'modify' => 1];
		if ($data['bookId'] && $data['bookName']){
			$params['bookId'] = $data['bookId'];
			$params['bookName'] = $data['bookName'];
		}
		$this->view->setVars($params);
	}

	/**
	 * 保存撤销教辅申请的信息
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180709
	 */
	public function saveReferenceRepealAction(){
		$data = $this->request->getPost();
		$referenceRepeal = new XhresReferenceRepeal();
		$referenceRepeal->iStatus = 0;
		$referenceRepeal->iSchoolId = trim($data['school']);
		$referenceRepeal->sAppCode = trim($data['application']);
		$referenceRepeal->iClassId = trim($data['grade']);
		$referenceRepeal->iSubject = trim($data['subject']);
		$referenceRepeal->iBookId = trim($data['referenceId']);
		$referenceRepeal->sBookName = trim($data['bookName']);
		$referenceRepeal->sTeacherList = !empty($data['teacher']) ? implode(',', $data['teacher']) : '';
		$referenceRepeal->iTeacherNum = !empty($data['teacher']) ? count($data['teacher']) : null;
		$referenceRepeal->sRemark = $data['remark'];
		if (!$referenceRepeal->save()){
			return $this->sendErrorResponse(500, '保存失败', $referenceRepeal->getError());
		} else {
			return $this->sendSuccessResponse('成功');
		}
	}

	/**
	 * 修改撤销教辅申请数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180709
	 */
	public function saveModifyReferRepealAction(){
		$data = $this->request->getPost();
		if ($data['iId'] && $data['iId'] < 0){
			return $this->sendErrorResponse(400, '缺少ID，修改失败');
		}
		$referenceRepeal = XhresReferenceRepeal::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $data['iId']]]);
		if (!$referenceRepeal){
			return $this->sendErrorResponse(500, '找不到数据');
		}
		if (User::getId() == $referenceRepeal->iCreateUserId && $referenceRepeal->iStatus == 2){
			$referenceRepeal->iStatus = 0;
		}
		$referenceRepeal->iSchoolId = trim($data['school']);
		$referenceRepeal->sAppCode = trim($data['application']);
		$referenceRepeal->iClassId = trim($data['grade']);
		$referenceRepeal->iSubject = trim($data['subject']);
		$referenceRepeal->sTeacherList = !empty($data['teacher']) ? implode(',', $data['teacher']) : '';
		$referenceRepeal->iTeacherNum = !empty($data['teacher']) ? count($data['teacher']) : null;
		$referenceRepeal->sRemark = $data['remark'];
		if (!$referenceRepeal->save()){
			return $this->sendErrorResponse(500, '修改失败', $referenceRepeal->getError());
		} else {
			return $this->sendSuccessResponse('修改成功');
		}
	}

    /**
     * 获取枚举中的学科信息
     *
     * @return array|bool
     *
     * create by qgz 20181123
     */
	public function getEnumClass()
    {
        $data = XhsysEnum::getEnumByNodeName('学科');
        if ($data){
            foreach ($data as $key => &$value){
                if ($value == '文综') {
                    unset($data[$key]);
                }
            }
        }
        return $data;
    }

    /**
     * 获取出版社枚举
     *
     * @return array
     *
     * create by qgz 20190226
     */
    public function getBookTypeEnum()
    {
        $return = [];
        $books = new Books();
        $bookType = $books->getBookType();
        if (!$bookType) {
            return $return;
        }
        if (isset($bookType['bookTypeResponseList']) && $bookType['bookTypeResponseList']) {
            foreach ($bookType['bookTypeResponseList'] as $value) {
                $return[$value['bookTypeCode']] = $value['bookTypeName'];
            }
        }
        return $return;
    }

    /**
     * 教辅书申请页
     *
     * @return \Phalcon\Mvc\View|string
     * @throws \Helpers\XhException
     *
     * create by qgz 20180604
     */
    public function referenceApplyAction(){
        $this->view->pick('res/referenceApply');
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/res/referenceApply.js');
        if (!UserPower::checkUserPower('Res_ReferenceApply')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        $listSearchArr = $listButtonArr = [];
        $power['check'] = $power['edit'] = 1;
        $listSearchArr[] = [
            'type' => 'select', 'id' => 'list_search_status','style' => 'width: 80px;',
            'data' => ['' => '-申请状态-'] + $this->registerEnum['referenceApply']['iStatus']
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_app',
            'style' => 'width:100px;', 'data' => ['' => '-选择应用-'] + App::getAppCodes()];
        $listSearchArr[] = ['label' => '    ','type' => 'select', 'id'=>'school_area', 'style' => 'width: 120px;'];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_publish',
            'data' => ['' => '-录入状态-'] + $this->registerEnum['referenceApply']['iPublishStatus']
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_plan',
            'data' => ['' => '-排期计划-'] + $this->registerEnum['referenceApply']['iExistPlan']
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_existId',
            'data' => ['' => '-存在id-'] + $this->registerEnum['referenceApply']['bExistBookId']
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_applySubject','multiple' => true,
            'data' => ['' => '-申请科目-'] + $this->getEnumClass(),'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_applyClass','multiple' => true,
            'data' => ['' => '-申请年级-'] + XhsysEnum::getEnumByNodeName('年级'), 'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_applyVolume','multiple' => true,
            'data' => ['' => '-上下册-'] + [1 => '上册', 2 => '下册', 3 => '全册'], 'style' => 'width: 75px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_bookSubject', 'multiple' => true,
            'data' => ['' => '-书本科目-'] + $this->getBookSubjectEnum('subject'),'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_bookClass', 'multiple' => true,
            'data' => ['' => '-书本年级-'] + $this->getBookSubjectEnum('grade'),'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_bookType', 'multiple' => true,
            'data' => ['' => '-出版社-'] + $this->getBookTypeEnum(),'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_bookComplete',
            'data' => ['' => '-完成状态-'] + $this->registerEnum['referenceApply']['iCompleteStatus'],'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_refuseHandle',
            'data' => ['' => '-拒绝状态-'] + $this->registerEnum['referenceApply']['iRefuseHandle']
        ];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search_startTime', 'label' => ' 创建时间：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search_endTime', 'label' => ' ~ '];
        $listSearchArr[] = [
            'label' => ' 搜索：','type' => 'select', 'id' => 'list_search_type', 'data' => ['1' => '编号', '2' => '书或学校']
        ];
//        $listSearchArr[] = ['type' => 'text', 'id' => 'list_iId','label' => '   编号：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
                            'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出',
                            'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];
        if (UserPower::checkUserPower('Res_ReferenceApply_Check')) {
            $power['isCheck'] = true;
            $power['check'] = 2;
            $listButtonArr[] = ['id' => 'bt_list_check', 'class' => 'menubutton', 'text' => '审核', 'plain' => 'true', 'icon' => 'fa-check'];
        }
        if (Power::exist('Res_ReferenceApply_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '取消申请', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        $listButtonArr[] = ['id' => 'bt_list_progress', 'text' => '查看进度', 'plain' => 'true', 'icon' => 'fa-flag'];
        if (Power::exist('Res_ReferenceApply_AddPlan')) {
            $listButtonArr[] = ['id' => 'bt_list_planApply', 'text' => '排期申请', 'plain' => 'true', 'icon' => 'fa-pencil-square-o'];
        }
        if (Power::exist('Res_ReferenceApply_EditPlan') || Power::exist('Res_SchedulePlan')) {
            $listButtonArr[] = ['id' => 'bt_list_planDetail', 'text' => '排期计划', 'plain' => 'true', 'icon' => 'fa-calendar-check-o'];
        }
        if (Power::exist('Res_ReferenceApply_RefuseHandle')) {
            $listButtonArr[] = ['id' => 'bt_list_refuseHandle', 'text' => '拒绝处理', 'plain' => 'true', 'icon' => 'fa-hand-paper-o'];
        }
        if (Power::exist('Res_ReferenceApply_CommitView') || Power::exist('Res_ReferenceApply_CommitEdit')) {
            $listButtonArr[] = ['id' => 'bt_list_refuseCommit', 'text' => '拒绝沟通', 'plain' => 'true', 'icon' => 'fa-commenting-o'];
            if (Power::exist('Res_ReferenceApply_CommitEdit')) {
                $power['commitEdit'] = true;
            }
        }
        if (Power::exist('Res_ReferenceApply_CheckTypeIn')) {
            $listButtonArr[] = ['id' => 'bt_list_checkTypeIn', 'text' => '录入确认', 'plain' => 'true', 'icon' => 'fa-handshake-o'];
        }
        $listButtonArr[] = ['id' => 'bt_list_refresh', 'text' => '刷新书本状态', 'plain' => 'true', 'icon' => 'fa-refresh'];
        $listButtonArr[] = ['id' => 'bt_list_teaStat', 'text' => '教师统计', 'plain' => 'true', 'icon' => 'fa-table'];
        $listButtonArr[] = ['id' => 'bt_list_showDetail', 'text' => '使用情况', 'plain' => 'true', 'icon' => 'fa-bars'];
        if (UserPower::checkUserPower('Res_ReferenceApply_Edit')) {
            $power['edit'] = 2;
        }
        if (Power::exist('Res_SchedulePlan_Add')) {
            $power['add'] = true;
        }
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHRes_ReferenceApply', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'power' => $power,
            'userId' => User::getId()
        ]);
    }

    /**
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by qgz 20180605
     * modify by qgz 20180620 增加区域选择
     */
    /**
     * 获取教辅书申请数据
     *
     * @param array $existParams
     *
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     * create by qgz 20180605
     * modify by qgz 20180620 增加区域选择
     * modify by qgz 20181120 如果有参数，用传入的参数
     */
    public function getReferenceApplyAction($existParams = [])
    {
        $search = $this->request->getPost('search');
        $sort = $this->request->getPost('sort');
        $order = $this->request->getPost('order');
        $comId = $this->request->getPost('comId');//组和id，学校_学科_年级,在查看老师详情用到
        $parameters = [
            'columns' => '*',
            'conditions' => ' bDelete = 0 ',
            'order' => 'tCreateDate DESC'
        ];
        if (!empty($existParams)) {
            $search = $existParams;
        }
        if ($search['status'] != ''){
            $parameters['conditions'] .= " AND iStatus = " . $search['status'];
        }
        if ($search['publish'] !== '' && $search['publish'] !== null){
            $parameters['conditions'] .= " AND iPublishStatus = " . $search['publish'];
        }
        if ($search['plan'] !== '' && $search['plan'] !== null){//查询是否有排期类型
//            $parameters['conditions'] .= " AND iExistPlan = " . $search['plan'];
            $bookIdArr = $this->getBookIdArr($search['plan']);
            if ($search['plan'] == 0 && $bookIdArr) {
                $parameters['conditions'] .= " AND iBookId NOT IN ({iBookId:array})";
                $parameters['bind'] = ['iBookId' => $bookIdArr];
            } elseif ($search['plan'] != 0) {
                if (!$bookIdArr) {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                } else {
                    $parameters['conditions'] .= " AND iBookId IN ({iBookId:array})";
                    $parameters['bind'] = ['iBookId' => $bookIdArr];
                }
            }
        }
        if ($search['app']){
            $parameters['conditions'] .= " AND sAppCode = '{$search['app']}' ";
        }
        if ($search['existId'] !== '' && $search['existId'] !== null) {
            $parameters['conditions'] .= " AND bExistBookId = " . $search['existId'];
        }
        if ($search['bookSubject'] !== '' && $search['bookSubject'] !== null) {
            $bookSubjectStatus = $this->handleSearchStatus($search['bookSubject']);
            if ($bookSubjectStatus) {
                $parameters['conditions'] .= " AND iBookSubject in ($bookSubjectStatus)";
            }
        }
        if ($search['bookClass'] !== '' && $search['bookClass'] !== null) {
            $bookClassStatus = $this->handleSearchStatus($search['bookClass']);
            if ($bookClassStatus) {
                $parameters['conditions'] .= " AND iBookClass in ($bookClassStatus)";
            }
        }
        if ($search['bookType'] !== '' && $search['bookType'] !== null) {
            $bookTypeStatus = $this->handleSearchStatus($search['bookType']);
            if ($bookTypeStatus) {
                $parameters['conditions'] .= " AND iBookType in ($bookTypeStatus)";
            }
        }
        if ($search['applySubject'] !== '' && $search['applySubject'] !== null) {
            $applySubjectStatus = $this->handleSearchStatus($search['applySubject']);
            if ($applySubjectStatus) {
                $parameters['conditions'] .= " AND iSubject in ($applySubjectStatus)";
            }
        }
        if ($search['applyClass'] !== '' && $search['applyClass'] !== null) {
            $applyClassStatus = $this->handleSearchStatus($search['applyClass']);
            if ($applyClassStatus) {
                $parameters['conditions'] .= " AND iClassId in ($applyClassStatus)";
            }
        }
        if ($search['applyVolume'] !== '' && $search['applyVolume'] !== null) {
            $applyVolumeStatus = $this->handleSearchStatus($search['applyVolume']);
            if ($applyVolumeStatus) {
                $parameters['conditions'] .= " AND iVolumeId in ($applyVolumeStatus)";
            }
        }
        if ($search['refuseHandle'] !== '' && $search['refuseHandle'] !== null) {
            $parameters['conditions'] .= " AND iRefuseHandle = " . $search['refuseHandle'];
        }
        if ($search['complete']) {
            $parameters['conditions'] .= " AND iCompleteStatus = " . $search['complete'];
        }
        if ($search['searchStartDate']) {
            $parameters['conditions'] .= " AND tCreateDate >= '{$search['searchStartDate']}'";
        }
        if ($search['searchEndDate']) {
            $parameters['conditions'] .= " AND tCreateDate <= '{$search['searchEndDate']}"." 23:59:59"."'";
        }
        $powerIds = School::getPower();
        if ($powerIds !== true) {
            if ($powerIds) {
                $parameters['conditions'] .= ' AND iSchoolId IN (' . implode(',', $powerIds) . ') ';
            } else {
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
        }
        $orConditions = $searchLineArr = [];
        if ($search['vague'] && $search['searchType'] == 2) {//普通搜索
            $searchLineArr = ['sBookName', 'iBookId'];
            $schools = School::searchSchool($search['vague']);
            $schoolIds = array_values($schools);
            if ($schoolIds){
                $schoolIds = implode("','", $schoolIds);
                $orConditions = [" iSchoolId in ('" . $schoolIds . "')"];
            }
        }
        if ($comId) {
            $comId = explode('_', $comId);
            $tchArr = $this->getTeachArr($comId[0], $comId[1], $comId[2]);
            if (!$tchArr) {
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
            $conditionArr = [];
            foreach ($tchArr as $tch) {
                $conditionArr[] = " CONCAT(',',sTeacherList,',') like '%,{$tch},%' ";//OR的关系
            }
            $conditionArr = implode(' OR ', $conditionArr);
            $parameters['conditions'] .= " AND (" . $conditionArr . ") ";
        }

        if ($search['vague'] && $search['searchType'] == 1) {//编号搜索
            if ($search['vague']) {
                if (is_numeric($search['vague'])) {
                    $parameters['conditions'] .= " and iId = '{$search['vague']}'";
                } else {
                    return $this->sendDataGridError('搜索编号请输入纯数字编号');
                }
            }
        }
        if (isset($search['school_area']) && !empty($search['school_area'])){//区域选择
            $depId  = $search['school_area'];
            $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
            $authId = $staff['iUserId'];
            if (!$authId) {//该地区没有负责人
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
            $schoolArr = User::getSchool(true, $authId, true);
            if (!empty($schoolArr)){
                $schoolIds = implode(',', array_keys($schoolArr));
                $parameters['conditions'] .= " and iSchoolId in ($schoolIds)";
            }
        }
        if ($sort && $order) {
            $parameters['order'] = "{$sort} {$order}";
        }
        Main::runSearchVagueConditions($parameters['conditions'], $searchLineArr, [], $orConditions);
        $enum = $this->registerEnum['referenceApply'];
        $enum['iClassId'] = XhsysEnum::getEnumByNodeName('年级');
        $enum['iSubject'] = XhsysEnum::getEnumByNodeName('学科');
        $enum['sAppCode'] = App::getAppCodes();
        $enum['iBookSubject'] = $this->getBookSubjectEnum('subject');
        $enum['iBookClass'] = $this->getBookSubjectEnum('grade');
        $enum['iBookType'] = $this->getBookTypeEnum();
        if (!empty($existParams)) {
            return $parameters;
        }
        $data = Main::runModelPage('Admin\Models\res\XhresReferenceApply', $parameters, $enum);
        Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
        Main::runUserName($data['rows'],['iCreateUserId' => 'sCreateUserName', 'iLastModifyUserId' => 'iLastModifyUserName']);
        $this->addOtherInfo($data, $enum);
        return $this->sendJsonResponse($data);
    }

    /**
     * 处理多选筛选参数
     *
     * @param $searchStatus
     *
     * @return array|string
     *
     * create by qgz 20181121
     */
    public function handleSearchStatus($searchStatus)
    {
        $return = [];
        if (!empty($searchStatus)){
            if (in_array('', $searchStatus) && count($searchStatus) == 1){
                $return = [];
            } elseif (in_array('', $searchStatus) && count($searchStatus) > 1){
                $return = array_diff($searchStatus, ['']);
                $return = implode(',', $return);
            } elseif (!in_array('', $searchStatus)){
                $return = implode(',', $searchStatus);
            }
        }
        return $return;
    }

    /**
     * 根据学校年级科目获取相应老师
     *
     * @param $school
     * @param $subject
     * @param $class
     *
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190218
     */
    public function getTeachArr($school, $subject, $class)
    {
        $return = [];
        if (!($school && $subject && $class)) {
            return $return;
        }
        $sql = "
SELECT a.iUserId
FROM
	XHSys_UserTch a
LEFT JOIN XHSys_User b ON a.iUserId = b.iUserId
WHERE
	a.iSubject = {$subject} AND a.iCurGrade = {$class} AND
	a.iUserId IN (
		SELECT
			iUserId
		FROM
			XHSys_User
		WHERE
			iSchoolId = {$school}
	)";
        $allTeaData = $this->db->fetchAll($sql);
        if (!$allTeaData) {
            return $this->sendJsonResponse($return);
        }
        return array_values(array_filter(array_unique(array_column($allTeaData, 'iUserId'))));
    }

    /**
     * 获取书本是否有排期计划数据，1有排期计划3已过期2新申请,存在即筛选
     *
     * @param $type
     *
     * @return array
     *
     * create by qgz 20181017
     */
    public function getBookIdArr($type)
    {
        $data = [];
        if ($type == 0) {
            $pro = XhresReferencePlan::find([
                'columns' => ' DISTINCT iBookId ',
                'conditions' => " bDelete = 0 and iBookId IS NOT null AND iBookId != '' AND iStatus != 4 "
            ])->toArray();
            return array_column($pro, 'iBookId');
        } else {
            $pro = XhresReferencePlan::find([
                'columns' => 'iBookId, sEndDate, sRealEndDate, iStatus',
                'conditions' => 'bDelete = 0 and iStatus != 4 '
            ]);
            $idArr = [];
            foreach ($pro as $value) {
                if ($value->iStatus != 4) {//取消的不计入
                    if ($value->sRealEndDate) {
                        if (isset($idArr[trim($value->iBookId)]) && in_array(1, $idArr[trim($value->iBookId)])) {
                            continue;
                        } else {
                            $idArr[trim($value->iBookId)][] = 1;//存在计划
                        }
                    } else {
                        if ($value->sEndDate) {
                            if (date('Y-m-d', time()) > $value->sEndDate) {
                                if (isset($idArr[trim($value->iBookId)]) && in_array(3, $idArr[trim($value->iBookId)])) {
                                    continue;
                                } else {
                                    $idArr[trim($value->iBookId)][] = 3;//过期
                                }
                            } else {
                                if (isset($idArr[trim($value->iBookId)]) && in_array(2, $idArr[trim($value->iBookId)])) {
                                    continue;
                                } else {
                                    $idArr[trim($value->iBookId)][] = 2;//新申请
                                }
                            }
                        }
                    }
                }
            }
            if ($idArr) {
                foreach ($idArr as $bookId => $statusArr) {
                    if (in_array($type, $statusArr)) {
                        $data[] = $bookId;
                    }
                }
            }
        }
        return $data;
    }

    /**
     * 根据书id获取排期计划类型 1有排期计划3已过期2新申请 有即加入
     *
     * @param $bookId
     *
     * @return array
     *
     * create by qgz 20181017
     */
    public function getPlanExistArrById($bookId)
    {
        $pro = XhresReferencePlan::find([
            'columns' => 'iBookId, sEndDate, sRealEndDate, iStatus',
            'conditions' => 'bDelete = 0 and iBookId = :iBookId: and iStatus != 4 ',
            'bind' => ['iBookId' => $bookId]
        ]);
        $idArr = [];
        if (!$pro) {
            return $idArr;
        }
        foreach ($pro as $value) {
            if ($value->iStatus != 4) {//取消的不计入
                if ($value->sRealEndDate) {
                    if (!in_array(1, $idArr)) {
                        $idArr[] = 1;//存在计划
                    }
                } else {
                    if ($value->sEndDate) {
                        if (date('Y-m-d', time()) > $value->sEndDate) {
                            if (!in_array(3, $idArr)) {
                                $idArr[] = 3;//过期
                            }
                        } else {
                            if (!in_array(2, $idArr)) {
                                $idArr[] = 2;//新申请
                            }
                        }
                    }
                }
            }
        }
        return $idArr;
    }

	/**
	 * 添加状态信息和审核说明
	 * @param $data // 数据
	 * @param $enum // 枚举
	 * @param $type // 类型，默认空获取值申请数据，2为撤销数据
	 * @return bool
	 *
	 * create by qgz 20180629
	 * modify by qgz 20180710 增加类型type
	 */
    public function addOtherInfo(&$data, $enum, $type='')
    {
    	if (!empty($data['rows'])) {
            $host = Main::getConfigByName('res');
		    foreach ($data['rows'] as &$value) {
			    $value['iStatusName'] = $value['iStatus'];
                $value['bookName'] = $value['sBookName'];
                $value['refuseHandleName'] = $value['iRefuseHandle'];
			    switch ($value['iStatus']){
			    	case $enum['iStatus']['0'] :
					    $value['checkResult'] = $type == 2 ? $value['sRecord'] : '';
					    $color = 'background-color: yellow';
					    break;
				    case $enum['iStatus']['1'] :
					    $value['checkResult'] = $type == 2 ? '（'.$value['iStatus'].'）' . $value['sRecord'] : $value['iStatus'];
					    if (!$type) {
                            $value['checkResult'] = $value['sRefuseReason'] ? '（'.$value['iStatus'].'）'.$value['sRefuseReason'] : $value['iStatus'];
                        }
					    $color = $type == 2 ? 'background-color: green;color:white' : 'background-color: #D8D8D8';
					    break;
				    case $enum['iStatus']['2'] :
				    	if ($type == 2){
						    $value['checkResult'] = '（'.$value['iStatus'].'）'.$value['sRecord'];
						    $color = 'background-color: red;color:white';
					    } else {
						    $value['checkResult'] = $value['sRefuseReason'] ? '（'.$value['iStatus'].'）'.$value['sRefuseReason'] : $value['iStatus'];
						    $color = 'background-color: green;color:white';
					    }
					    break;
				    case $enum['iStatus']['3'] :
					    $value['checkResult'] = '（拒绝）拒绝理由：' . $value['sRefuseReason'];
					    $color = 'background-color: red;color:white';
					    break;
				    case $enum['iStatus']['4'] :
					    $value['checkResult'] = $value['sRecomBook'] ? '（'.$value['iStatus'].'）'.$value['sRecomBook'] : $value['iStatus'];
					    $color = 'background-color: #87CEFA';
					    break;
                    case $enum['iStatus']['5'] :
                        $value['checkResult'] = $value['iStatus'];
                        $color = 'background-color: #FFA119';
                        break;
			    }
			    if (isset($value['checkResult']) && !empty($value['checkResult'])) {
				    $value['checkResult'] = '<div style="cursor:pointer" title="点击查看详情" class="checkResult" checkResult="'.$value['checkResult'].'" '.'><a>'.$value['checkResult'].'</a></div>';
			    }
			    if (isset($value['sRecord']) && !empty($value['sRecord'])) {
				    $value['checkResult'] = '<div style="cursor:pointer" title="点击查看详情" class="checkResult" checkResult="'.$value['sRecord'].'" '.'><a>'.$value['sRecord'].'</a></div>';
			    }
			    $value['iStatus'] = '<div style="'.$color.'">'.$value['iStatus'].'</div>';
			    $value['host'] = $host['outsideUrl'];

                switch ($value['iPublishStatus']) {
                    case $enum['iPublishStatus'][0] :
                        $publishColor = '#D8D8D8';
                        break;
                    case $enum['iPublishStatus'][1] :
                        $publishColor = '#87CEFA';
                        break;
                    case $enum['iPublishStatus'][2] :
                        $publishColor = 'yellow';
                        break;
                    case $enum['iPublishStatus'][3] :
                        $publishColor = '#FFA119';
                        break;
                    case $enum['iPublishStatus'][4] :
                        $publishColor = '#01A38F';
                        break;
                    case $enum['iPublishStatus'][5] :
                        $publishColor = 'red;color:white';
                        break;
                    default :
                        $publishColor = 'green;color:white';
                        break;
                }
                $value['iPublishStatus'] = '<div style=" background-color: '.$publishColor.'">'.$value['iPublishStatus'].'</div>';
                if ($value['iBookId']) {
                    $statusArr = $this->getPlanExistArrById($value['iBookId']);
                    if ($statusArr) {
                        $statusStr = '';
                        if (in_array(2, $statusArr)) {
                            $statusStr .= "<i title='该书有排期新申请' class='fa fa-thumb-tack' style='color:dodgerblue;'></i>  ";
                        }
                        if (in_array(3, $statusArr)) {
                            $statusStr .= "<i title='该书有排期已过期' class='fa fa-history' style='color:black;'></i>  ";
                        }
                        if (in_array(1, $statusArr)) {
                            $statusStr .= "<i title='该书本已有排期计划' class='fa fa-flag' style='color:red;'></i>  ";
                        }
                        $value['bookName'] = $statusStr . $value['bookName'];
                    }
                }
                $value['iBookClass'] = $value['iBookClass'] ? : '';
                $value['iClassId'] .= $value['iVolumeId'] ? ($value['iVolumeId'] == 1 ? '(上)' : ($value['iVolumeId'] == 2 ? '(下)' : '(全)')) : '';
		    }
	    }
	    return true;
    }
    /**
     * 处理搜索
     *
     * @return array
     *
     * create by qgz 20180606
     */
    public function searchHandle($data, $arr = [], $search = ''){
        $return = [];
        foreach ($data as $value){
            foreach ($arr as $row){
                if (isset($value[$row])){
                    if (strpos($value[$row], $search) !== false){
                        $return[] = $value;
                        break;
                    }else{
                        continue;
                    }
                }
            }
        }
        return $return;
    }

    /**
     * 导出教辅申请数据
     *
     * @return bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190128
     */
    public function exportReferenceApplyAction()
    {
        $this->view->disable();
        $params = $this->request->getQuery();
        $handleParams = ['bookSubject', 'bookClass', 'applySubject', 'applyClass', 'applyVolume'];
        foreach ($handleParams as $handle_param) {
            $params[$handle_param] = $params[$handle_param] ? explode(',', $params[$handle_param]) : [];
        }
        try {
            $searchSql = $this->getReferenceApplyAction($params);
            $data = XhresReferenceApply::find($searchSql)->toArray();
            if ($data) {
                $enum = $this->registerEnum['referenceApply'];
                $enum['iClassId'] = XhsysEnum::getEnumByNodeName('年级');
                $enum['iSubject'] = XhsysEnum::getEnumByNodeName('学科');
                $enum['sAppCode'] = App::getAppCodes();
                $enum['iBookSubject'] = $this->getBookSubjectEnum('subject');
                $enum['iBookClass'] = $this->getBookSubjectEnum('grade');
                Main::runSchoolNameByIdStr($data, ['iSchoolId' => 'sSchoolName']);
                Main::runUserName($data,['iCreateUserId' => 'sCreateUserName', 'iLastModifyUserId' => 'iLastModifyUserName']);
                Tool::runEnum($data, $enum);
                foreach ($data as &$value) {
                    unset($value['sRefuseCommit']);
                    $value['iStatusName'] = $value['iStatus'];
                    $value['bookName'] = $value['sBookName'];
                    $value['refuseHandleName'] = $value['iRefuseHandle'];
                    switch ($value['iStatus']) {
                        case $enum['iStatus']['0'] :
                            $value['checkResult'] = '';
                            break;
                        case $enum['iStatus']['1'] :
                            $value['checkResult'] = $value['sRefuseReason'] ? '（'.$value['iStatus'].'）'.$value['sRefuseReason'] : $value['iStatus'];
                            break;
                        case $enum['iStatus']['2'] :
                            $value['checkResult'] = $value['sRefuseReason'] ? '（'.$value['iStatus'].'）'.$value['sRefuseReason'] : $value['iStatus'];
                            break;
                        case $enum['iStatus']['3'] :
                            $value['checkResult'] = '（拒绝）拒绝理由：' . $value['sRefuseReason'];
                            break;
                        case $enum['iStatus']['4'] :
                            $value['checkResult'] = $value['sRecomBook'] ? '（'.$value['iStatus'].'）'.$value['sRecomBook'] : $value['iStatus'];
                            break;
                        case $enum['iStatus']['5'] :
                            $value['checkResult'] = $value['iStatus'];
                            break;
                    }
                    $value['iBookClass'] = $value['iBookClass'] ? : '';
                    $value['iClassId'] .= $value['iVolumeId'] ? ($value['iVolumeId'] == 1 ? '(上)' : ($value['iVolumeId'] == 2 ? '(下)' : '(全)')) : '';
                    if ($value['sTeacherList']) {
                        $value['sTeacherList'] = explode(',', trim($value['sTeacherList']));
                        if ($value['sTeacherList']) {
                            $userNameArr = XhsysUser::getUserNameById($value['sTeacherList']);
                            $value['sTeacherList'] = implode(',', array_values($userNameArr));
                        }
                    }
                }
                unset($value);
            }
            $title = [
                'iId' => '编号',
                'iStatus' => "申请状态",
                'iRefuseHandle' => "拒绝状态",
                'sSchoolName' => "学校",
                'sAppCode' => "应用",
                'iClassId' => "申请年级",
                'iSubject' => "申请科目",
                'sCreateUserName' => "申请人",
                'bExistBookId' => "是否存在",
                'bookName' => "教辅书名",
                'iPublishStatus' => "录入状态",
                'iBookId' => "教辅书ID",
                'iBookSubject' => "书本科目",
                'iBookClass' => "书本年级",
                'iCompleteStatus' => "完成状态",
                'checkResult' => "审核说明",
                'sTypeIn' => "录入需求",
                'sProgress' => "当前进度",
                'sTeachProgress' => "教学进度",
                'iTeacherNum' => "教师数量",
                'sTeacherList' => "教师",
                'bPaperBook' => "是否纸质",
                'iReferenceNum' => "教辅数量",
                'bElectronic' => "电子教辅",
//                'sBuyUrl' => "购买地址",
                'sRemark' => "备注",
                'tCreateDate' => "创建时间",
            ];
            $dataArr = [];
            foreach ($data as $value) {
                $row = [];
                foreach ($title as $filed => $name) {
                    $row[$filed] = Tool::getValue($value, $filed);
                }
                $dataArr[] = $row;
            }
            unset($data);
            $fileName = '教辅申请表';
            Tool::exportExcelOnline($fileName, $title, $dataArr,'xlsx', ['autoWidth' => true, 'header' => ['title' => '教辅申请表']]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        return true;
    }

    /**
     * 获取地域信息
     *
     * @return mixed
     *
     * create by qgz 20180620
     */
    public function getDepDataAction(){
        try {
            $data  = Hrm::getDepArray('XHYYB', 2, true);
            Tool::replaceKey($data, ['child' => 'children']);
            array_unshift($data, ['id' => '', 'text' => '--选择区域--', 'children' => []]);
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 检查应用名是否有重复字段
     *
     * @return bool
     *
     * create by qgz 20180606
     */
    public function checkAppName($name=''){
        if (strpos($name, '(学生)') === false && strpos($name, '(教师)') === false
            && strpos($name, '(通用)') === false && strpos($name, '(家长)') === false
            && strpos($name, '（学生端）') === false && strpos($name, '(学生端)') === false){
            return false;
        }else{
            return true;
        }
    }

	/**
	 * 设置状态待确认
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180704
	 */
    public function confirmReferenceAction(){
	    $id = $this->request->getPost('id');
        $reason = $this->request->getPost('reason');
	    if (!$id){
		    return $this->sendErrorResponse(400, '参数有误');
	    }
	    try {
		    $ids = implode(',', $id);
		    $sql = "update XHRes_ReferenceApply set iStatus = 1, sRefuseReason = '{$reason}' where bDelete = 0 AND iStatus = 0 AND iId in ({$ids})";
		    $data = $this->db->execute($sql);
		    if (!$data){
		    	return $this->sendErrorResponse(500, '修改出错');
		    }
		    return $this->sendSuccessResponse('成功');
	    } catch (\Exception $e){
		    return $this->sendErrorResponse(500, '修改出错：' . $e->getMessage());
	    }
    }

    /**
     * 修改状态为已上架
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181031
     */
    public function setPutAwayAction()
    {
        $id = $this->request->getPost('id');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少请求参数');
        }
        $findData = XhresReferenceApply::find([
            'conditions' => 'bDelete = 0 and iId in ({idArr:array})',
            'bind' => ['idArr' => $id]
        ]);
        if (!$findData) {
            return $this->sendErrorResponse(500, '找不到数据');
        }
        foreach ($findData as $datum) {
            if ($datum->iStatus != 4) {
                return $this->sendErrorResponse(500, '只有状态[资料准备中]可操作');
            }
            $datum->iStatus = 5;
            if (!$datum->save()) {
                return $this->sendErrorResponse(500, '保存出错');
            }
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 设置状态为完成
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180606
     * modify by qgz 20180628 完成状态关联教师
     */
    public function setFinishStatusAction(){
        $postData = $this->request->getPost();
        $data = XhresReferenceApply::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
        if (!$data){
            return $this->sendErrorResponse(500, '没有数据');
        }
        $statusArr = array_flip($this->registerEnum['referenceApply']['iStatus']);
        $data->iStatus = $statusArr['完成'];
        $data->iBookId = $postData['bookId'];
        $data->sBookName = $postData['bookName'];
        $data->sRefuseReason .= empty($postData['note']) ? '' : '；审核完成说明：' . $postData['note'];
        $this->db->begin();
        $isConnectTea = $isConnectSchool = false;
	    $connectTeaNum = 0;
        $schoolArr = School::getSchools();
        if ($data->sAppCode == 'CA103001'){//云作业关联教师
	        if ($data->iBookId && $data->sTeacherList){
		        $userId = User::getId();
//		        $userLogoName = User::getLogonName($userId);
        		$params = [];
        		$teaIdArr = explode(',', $data->sTeacherList);
        		foreach ($teaIdArr as &$row){
			        $row = trim($row);
		        }
		        $teaNameArr = XhsysUser::getUserNameById($teaIdArr);
        		foreach ($teaIdArr as $id){
        		    if ($id) {
        		        $params[] = [
        		            'bookId'       => trim($data->iBookId),
                            'createUserId' => $userId,
                            'logonName'    => User::getLogonName($id),
                            'powerType'    => 2,
                            'userId'       => $id,
                            'userName'     => $teaNameArr[$id],
                            'schoolId'     => $data->iSchoolId,
                            'schoolName'   => $schoolArr[$data->iSchoolId],
                            ];
        		    }
		        }
		        try {
			        ResPrivilege::connectTeaBook($params);//关联教师操作
			        $isConnectTea = true;
			        $connectTeaNum = count($params);
		        }
		        catch (XhException $e) {
			        $this->db->rollback();
			        return $this->sendErrorResponse(500, '关联教师出错：'.$e->getMessage());
		        }
		        $data->sRefuseReason = '关联云作业' . $connectTeaNum . '个老师';
	        }
        } elseif ($data->sAppCode == 'CA101010' && $data->iBookId && $data->iSchoolId){//如果是刷题王关联学校
        	$params = [
		        'bookId' => $data->iBookId,
		        'packageName' => 'com.xh.abrutch',
		        'schoolId' => $data->iSchoolId,
		        'schoolName' => $schoolArr[$data->iSchoolId],
		        'userId' => User::getId()
	        ];
	        try {
		        ResPrivilege::connectTeaSchool($params);//关联学校操作
		        $isConnectSchool = true;
	        }
	        catch (XhException $e) {
		        $this->db->rollback();
		        return $this->sendErrorResponse(500, '关联学校出错：'.$e->getMessage());
	        }
        }
        if (!$data->save()){
        	$this->db->rollback();
            return $this->sendErrorResponse(500, '修改状态出错', $data->getError());
        }
        $this->db->commit();
	    $msg = '成功';
        if ($isConnectTea){
	        $msg = '成功，并云作业关联'.$connectTeaNum.'个老师';
        } elseif ($isConnectSchool){
	        $msg = '成功，并刷题王关联了相关学校';
        }
        return $this->sendSuccessResponse($msg);
    }

	/**
	 * 撤销教辅申请页
	 *
	 * @return \Phalcon\Mvc\View|string
	 * @throws \Helpers\XhException
	 *
	 * create by qgz 20180709
	 */
	public function referenceRepealAction(){
		$this->view->pick('res/referenceRepeal');
		$this->view->setTemplateBefore('listForm');
		Main::showNavPosition();
		Assets::select2();
		Assets::easyUI('js/res/referenceRepeal.js');
		if (!Power::exist('Res_ReferenceRepeal')) {
			return $this->sendViewError('对不起，您没有查看此页面的权限');
		}
		$listSearchArr = $listButtonArr = [];
		$power['check'] = $power['edit'] = 1;
		$listSearchArr[] = ['type' => 'select', 'id' => 'list_search_status', 'data' => ['' => '--请选择状态--'] + $this->registerEnum['referenceRepeal']['iStatus']];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_app', 'style' => 'width:120px;', 'data' => ['' => '--请选择应用--'] + App::getAppCodes()];
		$listSearchArr[] = ['label' => '    ','type'=>'select', 'id'=>'school_area', 'style' => 'width: 120px;'];
		$listSearchArr[] = ['type' => 'text', 'id' => 'list_iId','label' => '   编号：'];
		$listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
		if (Power::exist('Res_ReferenceRepeal_Check')) {
			$power['isCheck'] = true;
			$power['check'] = 2;
			$listButtonArr[] = ['id' => 'bt_list_check', 'class' => 'menubutton', 'text' => '审核', 'plain' => 'true', 'icon' => 'fa-check'];
		}
		if (Power::exist('Res_ReferenceRepeal_Edit')) {
			$power['edit'] = 2;
		}
		return $this->view->setVars([
			'List'          => Template::createList('list', 'XHRes_ReferenceRepeal', [
				'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
				'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
			]),
			'power' => $power,
			'userId' => User::getId()
		]);
	}

	/**
	 * 获取撤销教辅申请数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 * @throws \Helpers\XhException
	 *
	 * create by qgz 20180709
	 */
	public function getReferenceRepealAction(){
		$search = $this->request->getPost('search');
		$parameters = [
			'columns' => '*',
			'conditions' => ' bDelete = 0 ',
			'order' => 'tCreateDate DESC'
		];
		if ($search['status'] != ''){
			$parameters['conditions'] .= " AND iStatus = " . $search['status'];
		}
		if ($search['app']){
			$parameters['conditions'] .= " AND sAppCode = '{$search['app']}' ";
		}
		$powerIds = School::getPower();
		if ($powerIds !== true) {
		    if ($powerIds) {
		        $parameters['conditions'] .= ' AND iSchoolId IN (' . implode(',', $powerIds) . ') ';
		    } else {
		        return $this->sendJsonResponse(['rows' => [], 'total' => 0]);
		    }
		}
		$schoolConditions = [];
		if ($search['vague']) {
			$schools = School::searchSchool($search['vague']);
			$schoolIds = array_values($schools);
			if ($schoolIds){
				$schoolIds = implode("','", $schoolIds);
				$schoolConditions = [" iSchoolId in ('" . $schoolIds . "')"];
			}
		}
		if (isset($search['school_area']) && !empty($search['school_area'])){//区域选择
			$depId  = $search['school_area'];
			$staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
			$authId = $staff['iUserId'];
			if (!$authId) {//该地区没有负责人
			    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
			}
			$schoolArr = User::getSchool(true, $authId, true);
			if (!empty($schoolArr)){
				$schoolIds = implode(',', array_keys($schoolArr));
				$parameters['conditions'] .= " and iSchoolId in ($schoolIds)";
			}
		}
		if ($search['iId']) {
		    if (is_numeric($search['iId'])) {
		        $parameters['conditions'] .= " and iId = '{$search['iId']}'";
		    } else {
		        return $this->sendDataGridError('搜索编号请输入纯数字编号');
		    }
		}

		Main::runSearchVagueConditions($parameters['conditions'], ['sBookName'], [], $schoolConditions);
		$enum = $this->registerEnum['referenceRepeal'];
		$enum['iClassId'] = XhsysEnum::getEnumByNodeName('年级');
		$enum['iSubject'] = XhsysEnum::getEnumByNodeName('学科');
		$enum['sAppCode'] = App::getAppCodes();
		$data = Main::runModelPage('Admin\Models\res\XhresReferenceRepeal', $parameters, $enum);
		Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
		Main::runUserName($data['rows'],['iCreateUserId' => 'sCreateUserName', 'iLastModifyUserId' => 'iLastModifyUserName']);
		$this->addOtherInfo($data, $enum, 2);
		return $this->sendJsonResponse($data);
	}

    /**
     * 撤销关联教师
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180703
     * modify by qgz 20180928 刷题王取消权限
     */
    public function referRepPassAction(){
	    $id = $this->request->getPost('id');
	    $record = $this->request->getPost('record');
	    if (empty($id)){
	    	return $this->sendErrorResponse(400, '参数有误');
	    }
	    $params = [
	    	'columns' => '*',
		    'conditions' => 'bDelete = 0 and iId in ({idArr:array})',
		    'bind' => ['idArr' => $id]
	    ];
	    $this->db->begin();
	    $data = XhresReferenceRepeal::find($params);
	    if (empty($data)){
		    return $this->sendErrorResponse(500, '暂无数据');
	    }
	    $bookNum = 0;
	    $teacherNum = 0;
	    $schoolNum = false;
	    foreach ($data as $value){
	    	if ($value->iStatus != 0){//完成通过才可撤销
			    $this->db->rollback();
	    		return $this->sendErrorResponse(400, '状态已被审核，请重新选择');
		    }
	    }
	    foreach ($data as $value){
		    $teachList = [];
		    if (!empty($value->iBookId) && !empty($value->sTeacherList) && $value->sAppCode == 'CA103001'){//云作业的书id和教师id
			    $teachList = explode(',', $value->sTeacherList);
			    foreach ($teachList as &$item){
				    $item = trim($item);
			    }
			    $params = [
				    'bookId' => trim($value->iBookId),
				    'status' => -1,
				    'userIdList' => $teachList
			    ];
			    try {
				    ResPrivilege::repealConnect($params);//撤销关联教师-书本
				    $bookNum++;
				    $teacherNum += count($teachList);
			    }
			    catch (\Exception $e) {
			    	$this->db->rollback();
				    return $this->sendErrorResponse(500, '撤销关联云作业出错：'.$e->getMessage());
			    }
		    }
		    if ($value->sAppCode == 'CA101010' && $value->iBookId && $value->iSchoolId) {//刷题王撤销学校
                $params = [
                    'userId' => User::getId(),
                    'bookId' => trim($value->iBookId),
                    'packageName' => 'com.xh.abrutch',
                    'schoolId' => trim($value->iSchoolId)
                ];
                $schoolInfo = XhschoolInfo::findFirst(['conditions' => 'iSchoolId = :iSchoolId:', 'bind' => ['iSchoolId' => $value->iSchoolId]]);
                if ($schoolInfo) {
                    $params['schoolName'] = $schoolInfo->sSchoolName;
                }
                try {
                    ResPrivilege::repealConnectSchool($params);//取消关联学校操作
                    $schoolNum = true;
                } catch (\Exception $e) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '撤销关联学校接口出错：'.$e->getMessage());
                }
            }
		    $value->iStatus = 1;
		    $value->sRecord .= $record . (empty($teachList) ? '' : '；撤销关联云作业' . count($teachList) . '个老师；');
		    $value->sRecord .= '撤销了刷题王关联的1所学校';
		    if (!$value->save()){
			    $this->db->rollback();
			    return $this->sendErrorResponse(500, '修改状态出错');
		    }
	    }
	    $msg = $bookNum == 0 ? '没有需要撤销的书本；' : '成功，撤销了云作业关联的' . $bookNum . '本书共' . $teacherNum . '个老师；';
	    $msg .= $schoolNum == true ? '撤销了刷题王关联的相关学校' : '';
	    $this->db->commit();
	    return $this->sendSuccessResponse($msg);
    }

	/**
	 * 设置撤销教辅申请为未通过
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180709
	 */
    public function referRepRefuseAction(){
	    $id = $this->request->getPost('id');
	    $record = $this->request->getPost('recommend');
	    if (!$id){
		    return $this->sendErrorResponse(400, '参数有误');
	    }
	    $params = [
		    'columns' => '*',
		    'conditions' => 'bDelete = 0 and iId = :iId:',
		    'bind' => ['iId' => $id]
	    ];
	    $data = XhresReferenceRepeal::findFirst($params);
	    if (empty($data)){
		    return $this->sendErrorResponse(500, '暂无数据');
	    }
	    if ($data->iStatus != 0){//完成通过才可撤销
		    return $this->sendErrorResponse(400, '状态已审核，请重新选择');
	    }
	    $data->iStatus = 2;
	    $data->sRecord .= empty($record) ? '' : $record . '；';
	    if (!$data->save()){
		    return $this->sendErrorResponse(500, '修改状态出错');
	    }
	    return $this->sendSuccessResponse('成功');
    }

	/**
	 * 删除教辅申请
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180704
	 */
	public function delReferApplyAction(){
		$id = $this->request->getPost('id');
		if (!$id){
			return $this->sendErrorResponse(400, '参数有误');
		}
		$ids = implode(',', $id);
		$sql = "update XHRes_ReferenceApply set bDelete = 1 where bDelete = 0 AND iId in ({$ids})";
		$data = $this->db->execute($sql);
		if (!$data){
			return $this->sendErrorResponse(500, '删除失败');
		}
		return $this->sendSuccessResponse('成功');
	}

    /**
     * 设置状态为拒绝
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180606
     */
    public function setRefuseStatusAction(){
        $postData = $this->request->getPost();
        $data = XhresReferenceApply::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
        if (!$data) {
            return $this->sendErrorResponse(500, '没有数据');
        }
        $data->iStatus = 3;//拒绝
        $data->iRefuseHandle = 1;//拒绝处理中
        $data->sRefuseReason = $postData['refuseReason'];
        $checkData = [
            'checkType' => 1,
            'checkUser' => User::getId(),
            'checkDate' => date('Y-m-d H:i:s'),
            'checkNote' => $postData['refuseReason']
        ];
        $checkData = $this->handleJsonStr($data->sRefuseCommit, $checkData, 'refuse');
        $data->sRefuseCommit = $checkData;//记录拒绝操作
        if (!$data->save()) {
            return $this->sendErrorResponse(500, '保存出错', $data->getError());
        }
        //给创建人发短信
        $sendMsgInfo = [];
        $staffInfo = Hrm::getStaffInfo([$data->iCreateUserId]);
        if (isset($staffInfo[$data->iCreateUserId]) && $staffInfo[$data->iCreateUserId]) {
            $sendMsgInfo = $staffInfo[$data->iCreateUserId];
        }
        $msg = '您有一个教辅申请被拒绝，请及时处理；申请教辅书：' . $data->sBookName . '，教辅书id：' . $data->iBookId . '；拒绝原因：' . $postData['refuseReason'];
        try {
            if ($sendMsgInfo && isset($sendMsgInfo['phoneNumber']) && $sendMsgInfo['phoneNumber']) {
                Main::sendSMS($sendMsgInfo['phoneNumber'], $msg);
                $this->createCommitLog('发短信成功', '发送号码：' . $sendMsgInfo['phoneNumber'] . '内容：' . $msg);
            }
        } catch (\Exception $e) {
            if ($sendMsgInfo && isset($sendMsgInfo['phoneNumber']) && $sendMsgInfo['phoneNumber']) {
                $this->createCommitLog('发短信出错', '发送号码：' . $sendMsgInfo['phoneNumber'] . '内容：' . $msg . '错误信息：' . $e->getMessage());
            } else {
                $this->createCommitLog('发短信出错', '错误信息：' . $e->getMessage());
            }
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 设置拒绝处理状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181114
     */
    public function dealRefuseHandleAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['id']) {
            return $this->sendErrorResponse(400, '缺少参数申请id');
        }
        if (!in_array($postData['type'], [1, 2])) {
            return $this->sendErrorResponse(400, '设置类型错误');
        }
        $data = XhresReferenceApply::findFirst(['conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
        if (!$data) {
            return $this->sendErrorResponse(500, '没有数据');
        }
        $checkData = [
            'checkUser' => User::getId(),
            'checkDate' => date('Y-m-d H:i:s'),
            'checkNote' => $postData['reason']
        ];
        if ($postData['type'] == 1) {//同意
            $data->iRefuseHandle = 3;//已处理
            $checkData['checkType'] = 3;
        } elseif ($postData['type'] == 2) {//不同意
            $data->iRefuseHandle = 2;//待沟通
            $checkData['checkType'] = 2;
        }
        $checkData = $this->handleJsonStr($data->sRefuseCommit, $checkData, 'refuse');
        $data->sRefuseCommit = $checkData;
        if (!$data->save()) {
            return $this->sendErrorResponse(500, '数据保存出错', $data->getError());
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 处理拒绝沟通内容json字符串
     *
     * @param string $existStr
     * @param $addDataArr
     * @param string $type
     *
     * @return string
     *
     * create by qgz 20181116
     */
    public function handleJsonStr($existStr = '', $addDataArr, $type = 'refuse')
    {
        $return = $existStr;
        if (!$addDataArr || !in_array($type, ['refuse', 'commit'])) {
            return $return;
        }
        if (!$existStr) {
            if ($type == 'refuse') {
                $return = json_encode(['checkData' => [$addDataArr]]);
            } elseif ($type == 'commit') {
                $return = json_encode(['commitData' => [$addDataArr]]);
            }
        } else {
            $oldStr = json_decode($existStr, true);
            if ($type == 'refuse') {
                $oldStr['checkData'][] = $addDataArr;
            } elseif ($type == 'commit') {
                $oldStr['commitData'][] = $addDataArr;
            }
            $return = json_encode($oldStr);
        }
        return $return;
    }

    /**
     * 查看和设置拒绝沟通内容页
     *
     * @return \Phalcon\Mvc\View
     *
     * create by qgz 20181116
     */
    public function dealRefuseCommitAction()
    {
        $this->view->pick('res/refuseCommit');
        Assets::easyUI('js/res/refuseCommit.js');
        $id = $this->request->getQuery('id');
        if (!$id) {
            return $this->sendViewError('缺少id参数');
        }
        $data = [];
        $findData = XhresReferenceApply::findFirst([
            'columns' => 'iRefuseHandle, sRefuseCommit',
            'conditions' => 'bDelete = 0 and iId = :iId:',
            'bind' => ['iId' => $id]
        ]);
        if (!$findData) {
            return $this->sendViewError('没有数据');
        }
        $handleStatus = $findData->iRefuseHandle;
        $findData = json_decode($findData->sRefuseCommit, true);
        if (isset($findData['checkData']) && $findData['checkData']) {//拒绝或者不同意记录
            foreach ($findData['checkData'] as $datum) {
                $names = XhsysUser::getUserNameById([$datum['checkUser']]);
                $data[] = [
                    'date' => $datum['checkDate'],
                    'type' => $datum['checkType'] == 1 ? '拒绝' : ($datum['checkType'] == 2 ? '不同意拒绝' : '同意拒绝'),
                    'user' => isset($names[$datum['checkUser']]) ? $names[$datum['checkUser']] : '',
                    'msg' => $datum['checkNote']
                ];
            }
        }
        if (isset($findData['commitData']) && $findData['commitData']) {//沟通记录
            foreach ($findData['commitData'] as $datum) {
                $names = XhsysUser::getUserNameById([$datum['commitUser']]);
                $data[] = [
                    'date' => $datum['commitDate'],
                    'type' => '沟通',
                    'user' => isset($names[$datum['commitUser']]) ? $names[$datum['commitUser']] : '',
                    'msg' => $datum['commitNote']
                ];
            }
        }
        $power = Power::exist('Res_ReferenceApply_CommitEdit') && $handleStatus == 2 ? true : false;
        return $this->view->setVars([
            'data' => $data,
            'editPower' => $power
        ]);
    }

    /**
     * 保存沟通信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181116
     */
    public function saveRefuseCommitAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['id']) {
            return $this->sendErrorResponse(400, '缺少参数申请id');
        }
        if ($postData['commitMsg'] === '' || $postData['commitMsg'] === null) {
            return $this->sendErrorResponse(400, '请填写沟通内容');
        }
        $data = XhresReferenceApply::findFirst(['conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
        if (!$data) {
            return $this->sendErrorResponse(500, '没有数据');
        }
        if ($postData['isEnd'] == 1) {//已处理，不再沟通
            $data->iRefuseHandle = 3;
        }
        $commitData = [
            'commitUser' => User::getId(),
            'commitDate' => date('Y-m-d H:i:s'),
            'commitNote' => $postData['commitMsg'],
            'commitEnd' => $postData['isEnd']
        ];
        $commitData = $this->handleJsonStr($data->sRefuseCommit, $commitData, 'commit');
        $data->sRefuseCommit = $commitData;
        if (!$data->save()) {
            return $this->sendErrorResponse(500, '数据保存出错', $data->getError());
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 设置状态为需录入
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180606
     */
    public function setWriteStatusAction(){
        $postData = $this->request->getPost();
        if (empty($postData['id'])){
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $ids = implode("','", $postData['id']);
        $findData = XhresReferenceApply::findFirst(['columns' => '*', 'conditions' => "bDelete = 0 and iId in ('$ids') and iStatus = 2"]);
        if ($findData){
            return $this->sendErrorResponse(400, '存在已审核完成项，请重新选择');
        }
        if ($postData['recommendBook']){
            $sql = "update XHRes_ReferenceApply set iStatus = 4, sRecomBook = '{$postData['recommendBook']}' where bDelete = 0 AND iId in ('".$ids."')";
        } else {
            $sql = "update XHRes_ReferenceApply set iStatus = 4 where bDelete = 0 AND iId in ('".$ids."')";
        }
        $data = $this->db->execute($sql);
        if (!$data){
            return $this->sendErrorResponse(500, '保存出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 教辅申请统计
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20180614
     */
    public function referApplyStatAction(){
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/res/referApplyStat.js');
        if (!UserPower::checkUserPower('Res_ReferApplyStat')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search_startTime', 'label' => ' 开始时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search_endTime', 'label' => ' 结束时间： ');
        $listSearchArr[] = ['type'=>'select', 'id'=>'school_area', 'style' => 'width: 120px;'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHRes_ReferApplyStat', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ]);
    }

    /**
     * 获取教辅申请统计数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180614
     * modify by qgz 20180620 增加区域选择
     */
    public function getReferApplyStatAction(){
        $search = $this->request->getPost('search');
        $parameters = "bDelete = 0 AND iStatus != 3 ";
        if ($search['startTime']){
            $parameters .= " AND tCreateDate > '{$search['startTime']}'";
        }
        if ($search['endTime']){
            $parameters .= " AND tCreateDate < '{$search['endTime']}"." 23:59:59"."'";
        }
        $powerIds = School::getPower();
        if ($powerIds !== true) {
            if (!empty($powerIds)){
                $parameters .= ' AND iSchoolId IN (' . implode(',', $powerIds) . ') ';
            }else{
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
        }

        if (isset($search['school_area']) && !empty($search['school_area'])){//区域选择
            $depId  = $search['school_area'];
            $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
            $authId = $staff['iUserId'];
            if (!$authId) {//该地区没有负责人
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
            $schoolArr = User::getSchool(true, $authId, true);
            if (!empty($schoolArr)){
                $schoolIds = implode(',', array_keys($schoolArr));
                $parameters .= " AND iSchoolId in ($schoolIds)";
            }
        }

        $keySearchSql = $search['vague'] ? " WHERE B.sSchoolName LIKE '%{$search['vague']}%'" : '';
        $sql = [
            'columns'   => 'A.*, B.sSchoolName, C.allTeacherNum',
            'query'     => "SELECT :columns: FROM (SELECT iSchoolId, SUM(iTeacherNum) AS iTeacherNum FROM `XHRes_ReferenceApply` WHERE {$parameters} GROUP BY iSchoolId ) A 
                            LEFT JOIN `XHSchool_Info` B ON A.iSchoolId = B.iSchoolId
                            LEFT JOIN ( SELECT iSchoolId, COUNT(*) AS allTeacherNum FROM `XHSys_User` WHERE bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND iUserType = 4 GROUP BY iSchoolId ) C ON A.iSchoolId = C.iSchoolId " . $keySearchSql
        ];
        $data = Main::runSqlPage($sql);
        $ids = implode("','", array_column($data['rows'], 'iSchoolId'));
        $schoolTeacherData = XhresReferenceApply::find([
            'columns' => 'iSchoolId, sTeacherList',
            'conditions' => $parameters . " AND iSchoolId in ('$ids') "
        ])->toArray();
        $teacherListArr = $finaNum = [];
        foreach ($schoolTeacherData as $row){
            if (isset($teacherListArr[$row['iSchoolId']])){
                $teacherListArr[$row['iSchoolId']] = array_merge($teacherListArr[$row['iSchoolId']], explode(',', $row['sTeacherList']));
            }else{
                $teacherListArr[$row['iSchoolId']] = explode(',', $row['sTeacherList']);
            }

        }
        foreach ($teacherListArr as $key => $item){
            $finaNum[$key] = count(array_filter(array_unique($item)));
        }
        foreach ($data['rows'] as &$value){
//            $value['iTeacherNum'] = '<div style="cursor:pointer" title="点击查看详情" iSchoolId="'.$value['iSchoolId'].'" schoolName="'.$value['sSchoolName'].'"  '.' class="detail"><a>'.$finaNum[$value['iSchoolId']].'</a></div>';
            $value['iTeacherNum'] = isset($finaNum[$value['iSchoolId']]) ? $finaNum[$value['iSchoolId']] : '';
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 教辅申请统计详情页
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20180615
     */
    public function getTeaNumDetailAction(){
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        Main::showNavPosition();
        Assets::easyUI('js/res/referApplyDetail.js');
	    Assets::importMainJs('assets/easyui/datagrid-detailview.js');
	    $this->view->pick('res/referenceStat');
        return $this->view->setVars([
            'List'=> Template::createList('list', 'XHRes_ReferApplyDetail', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                'checkbox' => false,
            ])
        ]);
    }

    /**
     * 获取教辅申请老师申请详情数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180615
     */
    public function getReferApplyDetailAction(){
        $schoolId = $this->request->getPost('schoolId');
        if (!$schoolId){
            return $this->sendErrorResponse(400, '缺少学校id');
        }
        $teacherIdArr = [];
        $teacherLists = XhresReferenceApply::find(['columns' => 'sTeacherList, iBookId, sBookName', 'conditions' => 'bDelete = 0 AND iStatus != 3 AND iSchoolId = :iSchoolId:', 'bind' => ['iSchoolId' => $schoolId]])->toArray();
        if (!empty($teacherLists)){
            foreach ($teacherLists as $teacherList){
                if ($teacherList['sTeacherList']){
                    $explodeArr = explode(',', $teacherList['sTeacherList']);
                    if (!empty($explodeArr)){
                        $teacherIdArr = array_merge($teacherIdArr, $explodeArr);
                    }
                }
            }
            $teacherIdArr = array_unique($teacherIdArr);
        }
        $parameters = [
            'columns' => 'iUserId, sUserName',
            'conditions' => ' bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND iUserType = 4 AND iSchoolId = :iSchoolId:',
            'bind' => ['iSchoolId' => $schoolId]
        ];
        Main::runSearchVagueConditions($parameters['conditions'], ['sUserName']);
        $data = Main::runModelPage('Admin\Models\user\XhsysUser', $parameters);
        $this->handleBookTeachData($data['rows'], $teacherIdArr, $teacherLists);
        return $this->sendJsonResponse($data);
    }

	/**
	 * 处理教师申请书数据
	 *
	 * @return bool
	 *
	 * create by qgz 20180706
	 */
    public function handleBookTeachData(&$data, $teacherIdArr, $schoolData){
	    foreach ($data as &$row){
		    $row['children'] = [];
		    $row['status'] = in_array($row['iUserId'], $teacherIdArr) ? '<i class="fa fa-check" title="已申请" style="color:green;" ></i>' : '<i class="fa fa-close" title="未申请" style="color:red;" ></i>';
		    if (in_array($row['iUserId'], $teacherIdArr)){//只有申请的老师进行处理
			    foreach ($schoolData as $value){
				    if ($value['iBookId'] || $value['sBookName']){
					    $teachArr = explode(',', $value['sTeacherList']);
					    if (in_array($row['iUserId'], $teachArr)){
						    $row['children'][] = [
							    'bookId' => $value['iBookId'] ? $value['iBookId'] : '（无）',
							    'bookName' => $value['sBookName'] ? $value['sBookName'] : '（无）',
						    ];
					    }
				    }
			    }
		    }
		    $row['teaNum'] = count($row['children']);
		    $row['applyBook'] = '';
		    if (count($row['children']) != 0){
			    $row['applyBook'] = '共'.count($row['children']).'本书：';
		    	foreach ($row['children'] as $bookName){
				    $row['applyBook'] .= $bookName['bookName'].'；';
			    }
			    $row['applyBook'] = '<span title="点击+号查看详情">'.$row['applyBook'].'</span>';
		    }
	    }
    	return true;
    }

    /**
     * 教辅申请刷新发布、书本完成状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by qgz 20180921
     * modify by qgz 20181120
     */
    public function refreshPublishStatusAction()
    {
        $type = $this->request->getPost('type');
        $id = $this->request->getPost('id');
        $params =  $this->request->getPost('params');
        $bind = $findConditions = [];
        $conditions = " iBookId IS NOT NULL AND iBookId != '' ";
        switch ($type) {
            case 1://选择书本
                $conditions .= " AND iId IN ({iId:array}) AND bDelete = 0 AND iBookId != '' ";
                $bind['iId'] = $id;
                $findConditions = [
                    'conditions' => $conditions,
                    'bind' => $bind
                ];
                break;
            case 2:
                $conditions .= " AND bDelete = 0 AND iBookId != '' ";
                $findConditions = [
                    'conditions' => $conditions,
                ];
                break;
            case 3:
                $searchSql = $this->getReferenceApplyAction($params);
                $searchSql['conditions'] .= " AND " . $conditions;
                $findConditions = $searchSql;
                break;
        }
        $data = XhresReferenceApply::find($findConditions);
        if ($data) {
            foreach ($data as $value) {
                if ($value->iBookId) {
                    $books = new Books();//先按单个的来
                    $result = $books->getBookDetail($value->iBookId);
                    if ($result && $result['bookId'] == $value->iBookId) {
                        if ($value->iPublishStatus != 5) {//5已发布，不刷新
                            $value->iPublishStatus = $result['publishStatus'];
                        }
                        $value->iCompleteStatus = $result['bookComplete'];
                        $value->iBookType = $result['bookType'];
//                        $value->iBookClass = $result['gradeId'];
//                        $value->iBookSubject = $result['subjectId'];
                        if (!$value->save(null, null, true)) {
                            return $this->sendErrorResponse(
                                500,
                                '更新书出错,书id:' . $value->iBookId .',编号id:' . $value->iId
                            );
                        }
                    }
                }
            }
//            $bookInfo = $data->toArray();
//            $bookInfo = array_filter(array_unique(array_column($bookInfo, 'iBookId')));
//            if ($bookInfo) {
//                $books = new Books();
//                $result = $books->getBookDetailByArr(['bookIdList' => $bookInfo]);
//                if ($result) {
//                    $result = array_column($result, null, 'bookId');
//                    foreach ($data as $value) {
//                        if ($value->iBookId) {
//                            if (isset($result[$value->iBookId]) && !empty($result[$value->iBookId])) {
//                                $value->iPublishStatus = $result[$value->iBookId]['publishStatus'];
//                                $value->iCompleteStatus = $result[$value->iBookId]['bookComplete'];
//                                $value->iBookClass = $result[$value->iBookId]['gradeId'];
//                                $value->iBookSubject = $result[$value->iBookId]['subjectId'];
//                                if (!$value->save(null, null, true)) {
//                                    return $this->sendErrorResponse(
//                                        500,
//                                        '更新书出错,书id:' . $value->iBookId .',编号id:' . $value->iId
//                                    );
//                                }
//                            }
//                        }
//                    }
//                }
//            }
            return $this->sendSuccessResponse('成功');
        } else {
            return $this->sendSuccessResponse('成功，没有需要刷新的数据');
        }
    }

    /**
     * 排期申请页
     *
     * @return string
     *
     * create by qgz 20180927
     */
    public function addPlanApplyFormAction()
    {
        $id = $this->request->getQuery('id');
        $bookId = $this->request->getQuery('bookId');
        $bookName = $this->request->getQuery('bookName');
        $type = $this->request->getQuery('type');//1是从教辅申请页6从教辅排期页
        if (!$bookId || !$id) {
            return $this->sendViewError('缺少书id或记录id，不可提交申请');
        }
        Assets::datetimePicker();
        Assets::select2();
        Assets::easyUI('js/res/addPlanApplyForm.js');
        $maxDateArr = $this->getMaxDate($bookId, $type);
        if ($maxDateArr['type'] == 3) {
            return $this->sendViewError('该书有新申请未确定计划时间，暂不可再次申请。');
        }
        $this->view->pick('res/addPlanApplyForm');
        $params = [
            'id' => $id,
            'bookId' => $bookId,
            'bookName' => $bookName,
            'maxDateType' => $maxDateArr['type'],
            'maxDate' => $maxDateArr['date']
        ];
        return $this->view->setVars($params);
    }

    /**
     * 获取申请的最大时间
     *
     * @param string $bookId
     * @param string $type //1教辅申请页只按教辅申请的数据、6教辅排期按所有的 20181214回退都按所有
     *
     * @return array
     *
     * create by qgz 20181023
     * modify by qgz 20181214 不加type限制
     */
    public function getMaxDate($bookId = '', $type = '')
    {
        $params = [
            'columns' => 'sStartDate, sEndDate, sRealStartDate, sRealEndDate',
            'conditions' => ' bDelete = 0 and iBookId = :iBookId: and iStatus != 4 and iStatus != 3',
            'bind' => ['iBookId' => $bookId]
        ];
//        if ($type == 1) {
//            $params['conditions'] .= ' and iAddType = 1 ';
//        }
        $date = XhresReferencePlan::find($params);
        $maxDate = '';//排期最大值
        $maxDateType = 1;//有排期最大值
        if ($date) {
            foreach ($date as $value) {
                if ($value->sEndDate && !$value->sRealEndDate) {//有新排期，
                    return ['type' => 3, 'date' => ''];
                    break;
                } else {//排期计划时间的最大值
//                    if ($value->sStartDate >= $maxDate) {
//                        $maxDate = $value->sStartDate;
//                    }
//                    if ($value->sEndDate >= $maxDate) {
//                        $maxDate = $value->sEndDate;
//                    }
                    if ($value->sRealStartDate >= $maxDate) {
                        $maxDate = $value->sRealStartDate;
                    }
                    if ($value->sRealEndDate >= $maxDate) {
                        $maxDate = $value->sRealEndDate;
                    }
                }
            }
        }
        if (!$maxDate || $maxDate < date('Y-m-d', time())) {
            $maxDate = date('Y-m-d', time());//没有排期或最大时间小于当前，取当前
            $maxDateType = 2;
        } else {
            $maxDate = $this->handleEndDate($maxDate, 2);
        }
        return ['type' => $maxDateType, 'date' => $maxDate];
    }

    /**
     * 展示章节树页面，type1是教辅申请页中，2是增加排期页中
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181011
     */
    public function showPlanCateLogTreeAction()
    {
//        Assets::easyUI('js/res/showCateLogTree.js');
        Assets::select2();
        $this->view->pick('res/showPlanCateLogTree');
        $id = $this->request->getQuery('id');
        $bookId = $this->request->getQuery('bookId');
        $type = $this->request->getQuery('type');
        if (!$bookId) {
            return $this->sendViewError( '缺少书id');
        }
        try {
            $data = [];
            $voltParams = ['type' => $type, 'id' => $id, 'treeName' => '', 'treeData' => json_encode([])];
            $params = [
                'textBookVersion' => 1,
                'gradeId' => 1,
                'subjectId' => 1
            ];//这三个参数传任意非空数据即可
            $books = new Books();
            $result = $books->getCatalogsByBookId($bookId, $params);
            if (!$result) {
                return $this->view->setVars($voltParams);
            }
            if (isset($result['bookName'])) {
                $voltParams['treeName'] = $result['bookName'];
            }
            if (isset($result['catalogs']) && $result['catalogs']) {
                foreach ($result['catalogs'] as $value) {
                    $data[] = [
                        'id' => $value['catalogId'],
                        'name' => $value['catalogName'],
                        'pId' => $value['parentCatalogId'],
                        'publishStatus' => $value['publishStatus'],
                        'spread' => true,
                        'open' => true
                    ];
                }
            }
            $voltParams['treeData'] = json_encode($data);
            return $this->view->setVars($voltParams);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 根据书id获取书章节数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180927
     */
    public function getCatalogsByBookIdAction()
    {
        $bookId = $this->request->getPost('bookId');
        if (!$bookId) {
            return $this->sendErrorResponse(400, '缺少书id');
        }
        try {
            $data = [];
            $params = [
                'textBookVersion' => 1,
                'gradeId' => 1,
                'subjectId' => 1
            ];//这三个参数传任意非空数据即可
            $books = new Books();
            $result = $books->getCatalogsByBookId($bookId, $params);
            if (!$result) {
                return $this->sendSuccessResponse($data);
            }
            if (isset($result['catalogs']) && $result['catalogs']) {
                foreach ($result['catalogs'] as $value) {
                    $name = $this->handleCateLogName($result['catalogs'], $value['catalogId']);
                    $data[] = ['id' => $value['catalogId'], 'text' => $name];
                }
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 拼接展示的章节名字,最高层章+节
     *
     * @param $data
     * @param $id
     * @param $type 1获取最高层章名2最高层章id
     *
     * @return string
     *
     * create by qgz 20181011
     */
    public function handleCateLogName($data, $id, $type = 1)
    {
        foreach ($data as $value) {
            if ($value['catalogId'] == $id && $value['parentCatalogId'] == 0) {
                return $type == 1 ? $value['catalogName'] : $value['catalogId'];
            }
            if ($value['catalogId'] == $id) {
                $selfName = $value['catalogName'];
                $parentName = $this->handleParentName($data, $id, $type);
                return $type == 1 ? $parentName . '_' . $selfName : $parentName;
            }
        }
    }

    /**
     * 递归找到最高层的名字
     *
     * @param $data
     * @param $id
     * @param $type 1获取最高层章名2最高层章id
     * @return mixed
     *
     * create by qgz 20181011
     */
    public function handleParentName($data, $id, $type)
    {
        foreach ($data as $value) {
            if ($value['catalogId'] == $id && $value['parentCatalogId'] == 0) {
                return $type == 1 ? $value['catalogName'] : $value['catalogId'];
            }
            if ($value['catalogId'] == $id) {
                if ($value['parentCatalogId'] != 0) {
                    return $this->handleParentName($data, $value['parentCatalogId'], $type);
                }
            }
        }
    }

    /**
     * 添加排期申请
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180921
     */
    public function addPlanApplyAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['id'] || !$postData['bookId']) {
            return $this->sendErrorResponse(400, '缺少申请id或书id参数');
        }
        if (!$postData['progress'] || !$postData['demand'] || !$postData['beginDate'] || !$postData['endDate']) {
            return $this->sendErrorResponse(400, '请填写完整信息');
        }
        if ($postData['beginDate'] > $postData['endDate']) {
            return $this->sendErrorResponse(400, '开始时间不能大于结束时间');
        }
        $endData = $this->handleEndDate($postData['beginDate'], 5);
        if ($postData['endDate'] < $endData) {
            return $this->sendErrorResponse(400, '时间间隔不能低于5个工作日');
        }
        if ($postData['beginDate'] < date('Y-m-d', time())) {
            return $this->sendErrorResponse(400, '开始时间不能早于当前');
        }
        $maxDateArr = $this->getMaxDate($postData['bookId'], $postData['type']);
        if ($maxDateArr['type'] == 3) {
            return $this->sendErrorResponse(400, '该书有新申请未确定计划时间，暂不可再次申请');
        }
        if ($postData['beginDate'] < $maxDateArr['date']) {
            return $this->sendErrorResponse(400, '请选择正确的开始时间');
        }
        $checkDemand = $this->checkDemandData($postData['bookId'], $postData['demand']);
        if (!$checkDemand) {
            return $this->sendErrorResponse(400, '有章节已经在排期内，不可重复选择');
        }
        $this->db->begin();
        //去掉是否新申请字段
//        if ($postData['type'] == 6) {
//            $applyPro = XhresReferenceSchedule::findFirst([
//                'conditions' => 'bDelete = 0 and iId = :iId:',
//                'bind' => ['iId' => $postData['id']]
//            ]);
//        } else {
//            $applyPro = XhresReferenceApply::findFirst([
//                'conditions' => 'bDelete = 0 and iId = :iId:',
//                'bind' => ['iId' => $postData['id']]
//            ]);
//        }
//        if (!$applyPro) {
//            $this->db->rollback();
//            return $this->sendErrorResponse(500, '找不到申请数据');
//        }
//        $applyPro->iExistPlan = 2;//新申请
//        if (!$applyPro->save()) {
//            $this->db->rollback();
//            return $this->sendErrorResponse(500, '更改状态错误');
//        }
        $bookName = '';
        $books = new Books();
        $result = $books->getBookDetail(trim($postData['bookId']));
        if ($result && $result['bookId'] == trim($postData['bookId'])) {
            $bookName = $result['bookName'];
        }
        $pro = new XhresReferencePlan();
        $pro->iApplyId = $postData['id'];
        $pro->iBookId = $postData['bookId'];
        $pro->sBookName = $bookName;
        $pro->sProgress = $postData['progress'];
        $pro->sDemand = $postData['demand'] ? implode(',', $postData['demand']) : '';
        $pro->sStartDate = $postData['beginDate'];
        $pro->sEndDate = $postData['endDate'];
        $pro->iAddType = $postData['type'];//1教辅申请页，6教辅排期页
        if (!$pro->save()) {//更新最后操作人
            $this->db->rollback();
            return $this->sendErrorResponse(500, '保存计划错误');
        }
        $this->db->commit();
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 根据$date日期获取$day个工作日后的日期
     *
     * @param $date
     * @param $day
     *
     * @return mixed
     *
     * create by qgz 20181011
     */
    public function handleEndDate($date, $day)
    {
        $dateArr = [];
        for ($i = 0; $i <= 30; $i++) {//最大是10天后的，设置$i为30，大即可
            $dateArr[] = date("Y-m-d",strtotime("+".$i." day",strtotime($date)));
        }
        $workDay = [];
        foreach ($dateArr as $item){
            if (!in_array(date('w', strtotime($item)), [0, 6])) {
                $workDay[] = $item;
            }
        }
        return $workDay[$day-1];
    }

    /**
     * 检查章节是否已经存在排期
     *
     * @param string $bookId
     * @param array $demand
     *
     * @return bool
     *
     * create by qgz 20181108
     */
    public function checkDemandData($bookId = '', $demand = [])
    {
        $findData = XhresReferencePlan::find([
            'columns' => 'sDemand',
            'conditions' => 'bDelete = 0 and iStatus != 3 and iStatus != 4 and iBookId = :iBookId: ',
            'bind' => ['iBookId' => $bookId]
        ])->toArray();
        if (!$findData) {
            return true;
        }
        $findData = array_filter(array_unique(array_column($findData, 'sDemand')));
        if (!$findData) {
            return true;
        }
        foreach ($demand as $value) {
            if (in_array($value, $findData)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 排期计划页面
     *
     * @return string
     *
     * create by qgz 20180921
     */
    public function applyPlanDetailAction()
    {
        $bookId = $this->request->getQuery('bookId');
        $id = $this->request->getQuery('id');
        $type = $this->request->getQuery('type');//1从教辅申请-排期计划页面，2从教辅排期(+排期查询页)-双击编辑页，3从排期计划-添加按钮页, 4从教辅排期
        $existBookId = $this->request->getQuery('existBookId');
        if (!$bookId && $type == 1) {
            return $this->sendViewError('缺少书本id');
        }
        if (!$id && $type == 1) {
            return $this->sendViewError('缺少申请id');
        }
        $this->view->pick('res/referApplyPlan');
        Assets::datetimePicker();
        Assets::select2();
        Assets::easyUI('js/res/referApplyPlan.js');
        $data = XhresReferencePlan::find([
            'conditions' => 'bDelete = 0 and iBookId = :iBookId:',
            'bind' => ['iBookId' => $bookId],
            'order' => 'sRealEndDate DESC, sRealStartDate DESC, sStartDate DESC, sEndDate DESC'
        ])->toArray();
        $catalogArr = $showCatalogArr = [];
        $params = [
            'textBookVersion' => 1,
            'gradeId' => 1,
            'subjectId' => 1
        ];//这三个参数传任意非空数据即可
        $books = new Books();
        $result = $books->getCatalogsByBookId($bookId, $params);//根据书id获取该书章节数据
        if (isset($result['catalogs']) && $result['catalogs']) {
            foreach ($result['catalogs'] as $value) {
                $catalogArr[$value['catalogId']] = $value['catalogName'];//列表中展示的章节
                $name = $this->handleCateLogName($result['catalogs'], $value['catalogId']);
                $showCatalogArr[$value['catalogId']] = $name;//下拉选择时展示的章节
            }
        }
        if ($data) {
            $applyIds = array_filter(array_unique(array_column($data, 'iApplyId')));
            if ($applyIds) {
                $applyIds = implode(',', $applyIds);
                $sql = "SELECT A.iId AS applyId, B.sSchoolName AS schoolName 
FROM XHRes_ReferenceApply A LEFT JOIN XHSchool_Info B ON A.iSchoolId = B.iSchoolId 
WHERE A.iId IN ($applyIds);";
                $schoolNameArr = $this->db->fetchAll($sql);
                if ($schoolNameArr) {
                    $schoolNameArr = array_column($schoolNameArr, 'schoolName', 'applyId');
                }
            } else {
                $schoolNameArr = [];
            }

            $isNeedAddColor = false;
            $demandFinishDate = '';
            if ($type == 1 || $type == 2) {
                $demandStatusDate = XhresReferenceNote::findFirst([
                    'columns' => 'sDemandFinishDate',
                    'conditions' => 'bDelete = 0 and iDateType = 1 and iStatus = 1 and iBookId = :iBookId:',
                    'bind' => ['iBookId' => $bookId]
                ]);
                if ($demandStatusDate) {
                    $isNeedAddColor = true;
                    $demandFinishDate = $demandStatusDate->sDemandFinishDate;
                }
            }
            $firstSchool = XhresReferencePlan::findFirst([
                'columns' => 'iId',
                'conditions' => "iApplyId is not null and iApplyId != '' and iBookId = :iBookId: and bDelete = 0 ",
                'bind' => ['iBookId' => $bookId],
                'order' => 'tCreateDate ASC',
                'limit' => 1
            ]);
            foreach ($data as &$value) {
                switch ($value['iStatus']) {
                    case 0 :
                        $value['iStatusStr'] = '未操作';
                        break;
                    case  1:
                        $value['iStatusStr'] = '<i style="color: green;font-style:normal">同意（默认）</i>';
                        break;
                    case  2:
                        $checkUser = XhsysUser::getUserNameById([$value['sCheckUser']]);
                        $value['iStatusStr'] = '<i style="color: green;font-style:normal">同意（' . $checkUser[$value['sCheckUser']] . '）</i>';
                        break;
                    case  3:
                        $checkUser = XhsysUser::getUserNameById([$value['sCheckUser']]);
                        $msg = '<i style="cursor:pointer;color: red" title="查看原因" class="reason fa fa-question-circle-o" reasonMsg="'.$value['sRefuseReason'].'" '.'></i>';
                        $value['iStatusStr'] = '<i style="color: blue;font-style:normal">不同意（' . $checkUser[$value['sCheckUser']] . '）</i>' . $msg;
                        break;
                    case 4:
                        $checkUser = XhsysUser::getUserNameById([$value['sCheckUser']]);
                        $msg = '<i style="cursor:pointer;color: red" title="查看原因" class="cancel fa fa-question-circle-o" cancelMsg="'.$value['sRefuseReason'].'" '.'></i>';
                        $value['iStatusStr'] = '<i style="color: red;font-style:normal">已取消（' . $checkUser[$value['sCheckUser']] . date('Y-m-d', strtotime($value['sCheckDate'])) . '）</i>' . $msg;
                        break;
                }
                if ($value['sDemand']) {
                    $demandArr = [];
                    $handDemand = explode(',', $value['sDemand']);
                    foreach ($handDemand as $item) {
                        $catalogId = ['catalogId' => $item];
                        $books = new Books();
                        $catalogInfo = $books->getCatalogsByCatalogId($catalogId);//根据章节id获取章节数据
                        if ($catalogInfo) {
                            $catalogInfo = array_column($catalogInfo, 'catalogName', 'catalogId');
                            if (isset($catalogInfo[$item]) && $catalogInfo[$item]) {
                                $demandArr[] = $catalogInfo[$item];
                            }
                        }
//                        if (isset($catalogArr[$item]) && $catalogArr[$item]) {
//                            $demandArr[] = $catalogArr[$item];
//                        }
                    }
                    if ($demandArr) {
                        $value['sDemand'] = implode('，', $demandArr);
                    }
                    $rootParentId = $this->handleCateLogName($result['catalogs'], $handDemand[0], 2);
                    if (!in_array($rootParentId, $handDemand)) {//加上最高层章节信息
                        $value['sDemand'] = isset($catalogArr[$rootParentId]) && $catalogArr[$rootParentId] ?
                            $catalogArr[$rootParentId] . '：' . $value['sDemand'] : $value['sDemand'];
                    }
                }
                //运营申请的加上申请学校信息
                $value['sDemand'] .= isset($schoolNameArr[$value['iApplyId']]) && $schoolNameArr[$value['iApplyId']] && $value['iAddType'] == 1 ?
                    ($firstSchool && $firstSchool->iId && $value['iId'] == $firstSchool->iId ?
                        '&nbsp&nbsp<label style="color:green;" title="该学校第一次申请该计划">【<i class="fa fa-star"></i>' . $schoolNameArr[$value['iApplyId']] . '】</label>' : '&nbsp&nbsp【' . $schoolNameArr[$value['iApplyId']] . '】'
                    ) : '';

                if ($isNeedAddColor && $demandFinishDate && $value['sRealEndDate']) {
                    if ($value['sRealEndDate'] < $demandFinishDate) {
                        $color = 'red';
                    } else if ($value['sRealEndDate'] == $demandFinishDate) {
                        $color = 'blue';
                    } else if ($value['sRealEndDate'] > $demandFinishDate) {
                        $color = 'green';
                    } else {
                        $color = 'black';
                    }
                    $value['sDemand'] = '<i style="color: ' . $color . ';font-style:normal">' . $value['sDemand'] . '</i>';
                }
                $value['isCreateMan'] = ($value['iCreateUserId'] == User::getId()) ? 1 : 2 ;//是否是申请人，结合操作按钮权限
                $modifyOrCreateUser = XhsysUser::getUserNameById([$value['iLastModifyUserId'], $value['iCreateUserId']]);
                $value['iLastModifyUserId'] = $modifyOrCreateUser[$value['iLastModifyUserId']];
                $value['iCreateUserId'] = $modifyOrCreateUser[$value['iCreateUserId']];
            }
        }
        $power = ['add' => false, 'del' => false, 'check' => false];
        if (Power::exist('Res_SchedulePlan_Add')) {
            $power['add'] = true;
        }
        if (Power::exist('Res_SchedulePlan_Del')) {
            $power['del'] = true;
        }
        if (Power::exist('Res_SchedulePlan_Check')) {
            $power['check'] = true;
        }
        return $this->view->setVars([
            'type' => $type,
            'existBookId' => $existBookId,
            'data' => $data,
            'catalogs' => $showCatalogArr,
            'power' => $power,
        ]);
    }

    /**
     * 教辅申请-排期计划--通过
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180921
     */
    public function checkTrueApplyPlanAction()
    {
        $id = $this->request->getPost('id');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        $data = XhresReferencePlan::findFirst([
            'conditions' => 'bDelete = 0 and iId = :iId:',
            'bind' => ['iId' => $id]
        ]);
        if (!$data) {
            return $this->sendErrorResponse(500, '暂无数据');
        }
        $data->iStatus = 2;
        $data->sCheckDate = date('Y-m-d H:i:s');
        $data->sCheckUser = User::getId();
        if (!$data->save()) {
            return $this->sendErrorResponse(500, '操作出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 教辅申请-排期计划--不通过
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180921
     */
    public function checkFalseApplyPlanAction()
    {
        $id = $this->request->getPost('id');
        $reason = $this->request->getPost('reason');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        try {
            $data = XhresReferencePlan::findFirst([
                'conditions' => 'bDelete = 0 and iId = :iId:',
                'bind' => ['iId' => $id]
            ]);
            if (!$data) {
                return $this->sendErrorResponse(500, '暂无数据');
            }
            $data->iStatus = 3;
            $data->sRefuseReason = $reason;
            $data->sCheckDate = date('Y-m-d H:i:s');
            $data->sCheckUser = User::getId();
            if (!$data->save()) {
                return $this->sendErrorResponse(500, '操作出错');
            }
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 取消排期计划
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180926
     */
    public function delApplyPlanAction()
    {
        $id = $this->request->getPost('id');
        $reason = $this->request->getPost('reason');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        try {
            $data = XhresReferencePlan::findFirst([
                'conditions' => 'bDelete = 0 and iId = :iId:',
                'bind' => ['iId' => $id]
            ]);
            if (!$data) {
                return $this->sendErrorResponse(500, '暂无数据');
            }
            $data->iStatus = 4;
            $data->sRefuseReason = $reason;
            $data->sCheckDate = date('Y-m-d H:i:s');
            $data->sCheckUser = User::getId();
            if (!$data->save()) {
                return $this->sendErrorResponse(500, '操作出错');
            }
            if (User::getId() != $data->iCreateUserId) {//给创建人发短信
                $staffInfo = Hrm::getStaffInfo([$data->iCreateUserId]);
                if (isset($staffInfo[$data->iCreateUserId]) && $staffInfo[$data->iCreateUserId]) {
                    $sendMsgInfo = $staffInfo[$data->iCreateUserId];
                    if ($sendMsgInfo['phoneNumber']) {
                        $msg = '你创建的教辅排期计划申请有被取消，请注意查看；取消原因：' . $reason . '，书名：' . $data->sBookName . '，书id：' . $data->iBookId;
                        //加上章节信息
                        $catalogArr = $result = [];
                        try {
                            $params = [
                                'textBookVersion' => 1,
                                'gradeId' => 1,
                                'subjectId' => 1
                            ];//这三个参数传任意非空数据即可
                            $books = new Books();
                            $result = $books->getCatalogsByBookId($data->iBookId, $params);//获取书章节数据
                            if (isset($result['catalogs']) && $result['catalogs']) {
                                foreach ($result['catalogs'] as $value) {
                                    $catalogArr[$value['catalogId']] = $value['catalogName'];//列表中展示的章节
                                }
                            }
                        } catch (\Exception $e) {
                            $this->createCommitLog('获取章节信息接口出错', '错误信息：' . $e->getMessage());
                        }
                        $demandArr = [];
                        $handDemand = explode(',', $data->sDemand);
                        foreach ($handDemand as $item) {
                            $catalogId = ['catalogId' => $item];
                            $books = new Books();
                            $catalogInfo = $books->getCatalogsByCatalogId($catalogId);//根据章节id获取章节数据
                            if ($catalogInfo) {
                                $catalogInfo = array_column($catalogInfo, 'catalogName', 'catalogId');
                                if (isset($catalogInfo[$item]) && $catalogInfo[$item]) {
                                    $demandArr[] = $catalogInfo[$item];
                                }
                            }
//                            if (isset($catalogArr[$item]) && $catalogArr[$item]) {
//                                $demandArr[] = $catalogArr[$item];
//                            }
                        }
                        if ($demandArr) {
                            $data->sDemand = implode('，', $demandArr);
                        }
                        if (isset($result['catalogs']) && $result['catalogs']) {
                            $rootParentId = $this->handleCateLogName($result['catalogs'], $handDemand[0], 2);
                            if (!in_array($rootParentId, $handDemand)) {//加上最高层章节信息
                                $data->sDemand = isset($catalogArr[$rootParentId]) && $catalogArr[$rootParentId] ?
                                    $catalogArr[$rootParentId] . '：' . $data->sDemand : $data->sDemand;
                            }
                        }
                        $msg .= '，申请排期章节：' . $data->sDemand . '。';
                        try {
                            Main::sendSMS($sendMsgInfo['phoneNumber'], $msg);
                            $this->createCommitLog('发短信成功', '发送号码：' . $sendMsgInfo['phoneNumber'] . '内容：' . $msg);
                        } catch (\Exception $e) {
                            $this->createCommitLog('发短信出错', '错误信息：' . $e->getMessage());
                        }
                    }
                }
            }
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 教辅申请-排期计划--保存
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180921
     */
    public function saveApplyPlanDataAction()
    {
        try {
            $postData = $this->request->getPost();
            if (!$postData['bookId']) {
                return $this->sendErrorResponse(400, '没有书id,不可保存');
            }
            $this->db->begin();
            $sendMsgArr = [];
            $needUpdate = false;
            if (isset($postData['handle']) && $postData['handle']) {//操作已经存在的
                foreach ($postData['handle'] as $datum) {
                    $data = XhresReferencePlan::findFirst([
                        'conditions' => 'bDelete = 0 and iId = :iId:',
                        'bind' => ['iId' => $datum['id']]
                    ]);

                    if (!$data) {
                        return $this->sendErrorResponse(500, '暂无数据,id:'.$datum['id']);
                    }
                    if (isset($datum['realStartDate']) && $datum['realStartDate']) {
                        $data->sRealStartDate = $datum['realStartDate'];
                        $needUpdate = true;
                    }
                    if (isset($datum['realEndDate']) && $datum['realEndDate']) {
                        $data->sRealEndDate = $datum['realEndDate'];
                        $data->sNoteDate = date('Y-m-d H:i:s');
                        if ($postData['type'] == 1 || $postData['type'] == 4) {//教辅申请页或教辅排期页发短信
                            if ($postData['type'] == 1) {
                                $applyData = XhresReferenceApply::findFirst([
                                    'conditions' => 'bDelete = 0 and iId = :iId:',
                                    'bind' => ['iId' => $data->iApplyId]
                                ]);
                            } else {
                                $applyData = XhresReferenceSchedule::findFirst([
                                    'conditions' => 'bDelete = 0 and iId = :iId:',
                                    'bind' => ['iId' => $data->iApplyId]
                                ]);
                            }
                            if (!$applyData) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(500, '找不到申请数据');
                            }
                            $sendMsgArr[] = [//发短信，类型1或6发给排期申请人2或5给教辅（或教辅排期）申请人
                                'createUser' => ($data->iAddType == 1 || $data->iAddType == 6) ? $data->iCreateUserId : (($data->iAddType == 2 || $data->iAddType == 5) ? $applyData->iCreateUserId : ''),
                                'bookId' => $postData['bookId'],
                                'bookName' => $data->sBookName,
                                'realStartDate' => $data->sRealStartDate,
                                'realEndDate' => $data->sRealEndDate,
                                'sDemand' => $data->sDemand
                            ];
                        }
                        $needUpdate = true;
                    }
                    if ($needUpdate) {
                        if (!$data->save()) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '保存数据失败,id:'.$datum['id']);
                        }
                    } else {
                        unset($data);
                    }
                }
            }
            if (isset($postData['addPlanList']) && $postData['addPlanList']) {//新增的申请
                $dealData = [];
                foreach ($postData['addPlanList'] as $key => $value) {
                    if ($key == 0) {//第一个是默认的，跳过
                        continue;
                    }
                    if (!isset($value['demand']) && !$value['realStartDate'] && !$value['realEndDate']) {
                        continue;
                    }
                    if (!(isset($value['demand']) && $value['realStartDate'] && $value['realEndDate'])) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(400, '新增申请需要填写完整信息');
                    }
                    if ($value['realStartDate'] > $value['realEndDate']) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(400, '开始时间不能大于结束时间');
                    }
                    $dealData[] = $value;
                }
                if ($dealData) {
                    $applyData = $bookName = '';
                    $books = new Books();
                    $result = $books->getBookDetail(trim($postData['bookId']));
                    if ($result && $result['bookId'] == trim($postData['bookId'])) {
                        $bookName = $result['bookName'];
                    }
                    if ($postData['type'] == 1 || $postData['type'] == 4) {//教辅申请页排期申请按钮、教辅排期页排期申请
                        $applyId = $postData['applyId'];
                        if ($postData['type'] == 1) {
                            $applyData = XhresReferenceApply::findFirst([
                                'conditions' => 'bDelete = 0 and iId = :iId:',
                                'bind' => ['iId' => $applyId]
                            ]);
//                            $bookName = $applyData->sBookName;
                        } else {
                            $applyData = XhresReferenceSchedule::findFirst([
                                'conditions' => 'bDelete = 0 and iId = :iId:',
                                'bind' => ['iId' => $applyId]
                            ]);
                        }
                        if (!$applyData) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '没有申请数据');
                        }
                    }
                    //保存书本学科、年级
                    $findData = XhresReferenceNote::findFirst([
                        'conditions' => ' bDelete = 0 and iBookId = :iBookId:',
                        'bind' => ['iBookId' => $postData['bookId']]
                    ]);
                    if (!$findData) {
                        $findData = new XhresReferenceNote();
                        $findData->iBookId = $postData['bookId'];
                    }
                    $findData->iStatus = $result['bookComplete'] == 1 ? 3 : 4;
                    $findData->iDateType = 2;
                    $findData->iBookSubject = $result['subjectId'];
                    $findData->iBookClass = $result['gradeId'];
                    if (!$findData->save()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '保存书本年级科目出错');
                    }
                    foreach ($dealData as $addData) {
                        $pro = new XhresReferencePlan();
                        if ($postData['type'] == 1 || $postData['type'] == 4) {//教辅申请id、教辅排期页的申请id（记录关联的申请id）
                            $pro->iApplyId = $postData['applyId'];
                        }
                        $pro->iBookId = $postData['bookId'];
                        $pro->sBookName = $bookName;
                        $pro->sProgress = isset($addData['progress']) && $addData['progress'] ? $addData['progress'] : '';
                        $pro->sDemand = implode(',', $addData['demand']);
    //                    $pro->sStartDate = isset($addData['startDate']) && $addData['startDate'] ? $addData['startDate'] : '';
    //                    $pro->sEndDate = isset($addData['endDate']) && $addData['endDate'] ? $addData['endDate'] : '';
                        $pro->sRealStartDate = $addData['realStartDate'];
                        $pro->sRealEndDate = $addData['realEndDate'];
                        $pro->sNoteDate = date('Y-m-d H:i:s');
//                        $pro->iAddType = $postData['type'] == 1 ? 2 :
//                            ($postData['existBookId'] == 1 ? 3 :
//                                ($postData['type'] == 4 ? 5 :
//                                    4));

                        //教辅申请--排期计划页为2，排期汇总页无id添加为3，有4(包括双击和选中后操作、排期查询页双击)，5教辅排期页
                        $pro->iAddType = $postData['type'] == 1 ? 2 :
                            (
                                $postData['type'] == 4 ? 5 :
                                    (
                                        $postData['existBookId'] == 1 ? 3 : 4
                                    )
                            );
                        if (!$pro->save()) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '保存新增申请数据出错');
                        }
                        if ($postData['type'] == 1 || $postData['type'] == 4) {//教辅申请或教辅排期页发短信
                            $sendMsgArr[] = [//发短信
                                'createUser' => $applyData->iCreateUserId,//给教辅申请人、教辅排期申请人
                                'bookId' => $postData['bookId'],
                                'bookName' => $bookName,
                                'realStartDate' => $addData['realStartDate'],
                                'realEndDate' => $addData['realEndDate'],
                                'sDemand' => $pro->sDemand
                            ];
                        }
                    }
                }
            }
            if ($postData['type'] == 4 && $postData['existBookId'] == 1) {//教辅排期页第一次添加把书id入库
                $referSchedule = XhresReferenceSchedule::findFirst([
                    'conditions' => 'bDelete = 0 and iId = :iId:',
                    'bind' => ['iId' => $postData['applyId']]
                ]);
                if (!$referSchedule) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '找不到书的申请数据');
                }
                $referSchedule->iBookId = $postData['bookId'];
                if (!$referSchedule->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '保存申请的书id数据出错');
                }
            }
            if ($sendMsgArr) {//给相关人发短信
                $this->sendMsg($sendMsgArr);
            }

            $this->db->commit();
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 发短信
     *
     * @param $data
     *
     * @return bool
     *
     * create by qgz 20180929
     */
    public function sendMsg($data)
    {
        if (empty($data)) {
            return true;
        }
        $user = $book = [];
        $bookId = '';
        foreach ($data as $value) {
            if (isset($value['createUser']) && isset($value['bookId']) && $value['createUser'] && $value['bookId']) {
                $user[$value['createUser']][$value['bookId']][] = $value;
                $book[$value['bookId']] = $value['bookName'];
                $bookId = $value['bookId'];
            }
        }
        $catalogArr = $showCatalogArr = [];
        $result['catalogs'] = [];
        if ($bookId) {//获取章节信息
            try {
                $params = [
                    'textBookVersion' => 1,
                    'gradeId' => 1,
                    'subjectId' => 1
                ];//这三个参数传任意非空数据即可
                $books = new Books();
                $result = $books->getCatalogsByBookId($bookId, $params);//获取书章节数据
                if (isset($result['catalogs']) && $result['catalogs']) {
                    foreach ($result['catalogs'] as $value) {
                        $catalogArr[$value['catalogId']] = $value['catalogName'];//列表中展示的章节
                    }
                }
            } catch (\Exception $e) {
                $this->createCommitLog('获取章节信息接口出错', '错误信息：' . $e->getMessage());
                return true;
            }
        }
        $userArr = array_keys($user);
        if (!$userArr) {
            return true;
        }
        $userStaffInfo = XhhrmStaff::find([
            'columns' => 'iUserId, sSelfPhone',
            'conditions' => 'bDelete = 0 and iUserId IN ({idArr:array})',
            'bind' => ['idArr' => $userArr]
        ])->toArray();
        if (!$userStaffInfo) {
            $this->createCommitLog('没有人员id', '部门表中找不到人员信息');
            return true;
        }
        $phoneNumArr = array_column($userStaffInfo, 'sSelfPhone', 'iUserId');
        if (!$phoneNumArr) {
            return true;
        }
        foreach ($user as $userId => $dataValue) {
            $msg = '教辅申请排期有新计划；';
            if (count($dataValue) == 1) {//只有一本书
                foreach ($dataValue as $bookId => $dateTime) {
                    $msg .= '书名：' . (isset($book[$bookId]) ? $book[$bookId] : '未知') . '；';
                    foreach ($dateTime as $value) {
                        //加上章节信息
                        $demandArr = [];
                        $handDemand = explode(',', $value['sDemand']);
                        foreach ($handDemand as $item) {
                            $catalogId = ['catalogId' => $item];
                            $books = new Books();
                            $catalogInfo = $books->getCatalogsByCatalogId($catalogId);//根据章节id获取章节数据
                            if ($catalogInfo) {
                                $catalogInfo = array_column($catalogInfo, 'catalogName', 'catalogId');
                                if (isset($catalogInfo[$item]) && $catalogInfo[$item]) {
                                    $demandArr[] = $catalogInfo[$item];
                                }
                            }
//                            if (isset($catalogArr[$item]) && $catalogArr[$item]) {
//                                $demandArr[] = $catalogArr[$item];
//                            }
                        }
                        if ($demandArr) {
                            $value['sDemand'] = implode('，', $demandArr);
                        }
                        if ($result['catalogs']) {
                            $rootParentId = $this->handleCateLogName($result['catalogs'], $handDemand[0], 2);
                            if (!in_array($rootParentId, $handDemand)) {//加上最高层章节信息
                                $value['sDemand'] = isset($catalogArr[$rootParentId]) && $catalogArr[$rootParentId] ?
                                    $catalogArr[$rootParentId] . '：' . $value['sDemand'] : $value['sDemand'];
                            }
                        }
                        $msg .= '计划时间：' . $value['realStartDate'] . '至' . $value['realEndDate'] . '、';
                        $msg .= '排期章节：' . $value['sDemand'] . '；';
                    }
//                    if (count($dateTime) == 1) {//计划时间只有一个
//                        $msg .= '计划开始结束时间：' . $dateTime[0]['realStartDate'] . '至' . $dateTime[0]['realEndDate'] . '；';
//                    } elseif (count($dateTime) > 1) {//计划时间有多个
//                        $msg .= '该书有多个排期计划日期，请悉知。';
//                    } else {
//                        continue;
//                    }
                    $msg .= '查看该书排期详情请点击：' . 'http://' . $_SERVER['HTTP_HOST'] . '/res/getPlanDetail?bookId=' . base64_encode($bookId);
                }
            }
//            elseif (count($dataValue) > 1) {//多本书
//                $msg .= '共' . count($dataValue) . '本书；书名：';
//                foreach ($dataValue as $bookId => $dateTime) {
//                    $msg .= (isset($book[$bookId]) ? $book[$bookId] : '未知') . '；';
//                }
//            }
            else {
                continue;
            }
            try {
                if (isset($phoneNumArr[$userId]) && $phoneNumArr[$userId]) {
                    Main::sendSMS($phoneNumArr[$userId], $msg);
                    $this->createCommitLog('发短信成功', '发送号码：' . $phoneNumArr[$userId] . '内容：' . $msg);
                }
            } catch (\Exception $e) {
                $this->createCommitLog('发短信出错', '错误信息：' . $e->getMessage());
                return true;
            }
        }
        return true;
    }

	/**
	 * 区域组列表页
	 *
	 * @return \Phalcon\Mvc\View|string
	 *
	 * create by qgz 20180725
	 */
    public function areaBookVersionAction(){
	    $this->view->pick('res/areaBookVer');
	    Main::showNavPosition();
	    Assets::select2();
	    Assets::easyUI('js/res/areaBookVerList.js');
	    if (!Power::exist('Res_AreaBookVerList')) {
		    return $this->sendViewError('无查看权限');
	    }
	    $listButtonArr = $formButtonArr = $listSearchArr = [];
	    $enumData = ['--学段--'] + $this->areaGroupEnum['iStage'];
	    $enumAreaType = $this->areaGroupEnum['areaType'];
	    $listSearchArr[] = ['type' => 'select', 'id' => 'list_stage', 'data' => $enumData, 'style' => 'width:75px;'];
	    $listSearchArr[] = ['type' => 'select', 'label' => '   搜索：', 'id' => 'list_area_type', 'data' => $enumAreaType, 'style' => 'width:60px;'];
	    $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
	    $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
	    $listSearchArr[] = ['type' => 'button', 'id' => 'list_outArea', 'text' => '查看待设置地区', 'icon' => 'fa-eye', 'style' => 'margin-left:10px'];
	    if (Power::exist('Res_AreaBookVerList_Add')) {
		    $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_add', 'text' => '添加区域组', 'icon' => 'fa-plus'];
	    }
	    if (Power::exist('Res_AreaBookVerList_Edit')) {
		    $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_edit', 'text' => '修改', 'icon' => 'fa-pencil'];
	    }
	    if (Power::exist('Res_AreaBookVerList_Del')) {
		    $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
	    }
	    return $this->view->setVars([
		    'List' => Template::createList('list', 'XHRes_AreaBookVer', [
			    'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
			    'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
			    'checkbox' => false
		    ])
	    ]);
    }

	/**
	 * 获取区域组列表数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180725
	 */
    public function getAreaBookVerDataAction(){
    	$page = $this->request->getPost('page');
	    $rows = $this->request->getPost('rows');
	    $stage = $this->request->getPost('stage');
	    $type = $this->request->getPost('type');
	    $search = $this->request->getPost('search');
	    $search = $search['vague'] ? $search['vague'] : '';
	    try {
		    $return = ['total' => 0, 'rows' => []];
            $area = [];
            if ($search) {
                switch ($type) {
                    case 1:
                        $area['provinceName'] = $search;
                        break;
                    case 2:
                        $area['cityName'] = $search;
                        break;
                    case 3:
                        $area['districtName'] = $search;
                        break;
                    default:
                        break;
                }
            }
		    $data = ResAreaGroup::getAreaGroupList($page, $rows, $stage, $area);
		    if (empty($data)){
			    return $this->sendJsonResponse($return);
		    }
		    $return['total'] = $data['totalCount'];
		    $data = $data['groupInfoListResponseList'];
		    $enumData = $this->areaGroupEnum['iStage'];
		    $valueNameArr = $this->getEnumTypeList();

//		    $return['total'] = 2;
//		    $data['rows'] = $this->listData;
//		    $data = json_decode($data['rows'], true);
		    if (!empty($data)){
			    foreach ($data as $key => $value){
				    $return['rows'][$key]['groupId'] = $value['groupId'];
				    $return['rows'][$key]['groupName'] = $value['groupName'];
				    $return['rows'][$key]['groupNameStr'] = $value['groupName'].'</br>'."({$enumData[$value['stageType']]})";
				    $return['rows'][$key]['iStage'] = $value['stageType'];
				    $return['rows'][$key]['subjVersion'] = $this->handleSubjVersion($value['groupTextBookDTOList'], $valueNameArr);
				    $return['rows'][$key]['area'] = $this->handleAreaData($value['groupDistrictResponseList'], $return['rows'][$key]['subjVersion']);
			    }
		    }
		    return $this->sendJsonResponse($return);
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500, $e->getMessage());
	    }
    }

	/**
	 * 处理学科版本信息
	 *
	 * @return string
	 *
	 * create by qgz 20180727
	 */
    public function handleSubjVersion($data, $enum){
    	$return = '';
    	$name = $exist = [];
	    foreach ($data as $id){
		    if (in_array($id['subjectId'].$enum['book'][$id['textBookVersion']], $name)){
			    $exist[] = $id['subjectId'].$enum['book'][$id['textBookVersion']];
		    } else {
			    $name[] = $id['subjectId'].$enum['book'][$id['textBookVersion']];
		    }
	    }
    	foreach ($data as $value){
		    if (in_array($value['subjectId'].$enum['book'][$value['textBookVersion']], $exist)){
			    $return .= $enum['subject'][$value['subjectId']].'：'.$enum['book'][$value['textBookVersion']].'_'.$value['textBookVersion'].'</br>';
		    } else {
			    $return .= $enum['subject'][$value['subjectId']].'：'.$enum['book'][$value['textBookVersion']].'</br>';
		    }
	    }
    	return $return;
    }

	/**
	 * 处理使用信息
	 *
	 * @return string
	 *
	 * create by qgz 20180727
	 */
    public function handleAreaData($data, $versionStr){
    	$return = '';
    	if (empty($data)){
    		return $return;
	    }
    	foreach ($data as $value){
    		if (!$return){
			    $return = $value['cityName'].$value['districtName'];
		    } else {
			    $return .= '、'.$value['cityName'].$value['districtName'];
		    }
	    }
	    $title = $return;
    	//计算长度
	    $num = intval(floor(mb_strlen($return, 'UTF-8')/23));//地区数据的长度
	    $existNum = substr_count($versionStr, 'br>');//版本信息的长度
	    if ($num <= $existNum){
		    if ($existNum > 1){
			    for ($i = 1; $i < $existNum; $i++){
				    $return = substr_replace($return,'</br>',23*3*$i+5*($i-1),0);//换行
			    }
		    }
	    } else {
	    	if ($existNum <= 4){//4行换行
			    $addNum = 4;
		    } else {
			    $addNum = $existNum;
		    }
		    for ($i = 1; $i < $addNum-1; $i++){
			    $return = substr_replace($return,'</br>',23*3*$i+5*($i-1),0);//换行
		    }
	    }
	    $return = '<span title="'.$title.'">'.$return.'</span>';
	    return $return;
    }

	/**
	 * 删除区域组
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180725
	 */
    public function delAreaBookVerAction(){
	    $id = $this->request->getPost('id');
	    if (!$id){
		    return $this->sendErrorResponse(400, '参数有误');
	    }
	    try {
		    ResAreaGroup::delGroupArea($id);
		    return $this->sendSuccessResponse('成功');
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500, $e->getMessage());
	    }
    }

	/**
	 * 未设置区域页面
	 *
	 *
	 * create by qgz 20180725
	 */
    public function getOutAreaAction(){
	    Assets::select2();
	    Assets::easyUI('js/res/outAreaForm.js');
	    $this->view->pick('res/outAreaForm');
    }

	/**
	 * 获取省数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180725
	 */
    public function getProvinceDataAction(){
	    try {
		    $areaObj = new Area();
		    $allData = $areaObj->getAllCodes();
		    foreach ($allData as $code => $name){
		    	if (substr($code, -4, 4) === '0000'){
		    		$return[] = ['id' => $code, 'text' => $name];
			    };
		    };
		    return $this->sendJsonResponse($return);
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500, $e->getMessage() );
	    }
    }

	/**
	 * 获取学段数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180730
	 */
	public function getStageDataAction(){
		$data = $this->areaGroupEnum['iStage'];
		foreach ($data as $key => $value){
			$return[] = ['id' => $key, 'text' => $value];
		}
		return $this->sendJsonResponse($return);
	}

	/**
	 * 区域组根据省获取未设置区域的市县
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180725
	 */
    public function getCityDataAction(){
	    $province = $this->request->getPost('province');
	    $province_name = $this->request->getPost('province_name');
	    $stage = $this->request->getPost('stage');
	    try {
		    if (!empty($stage) && !empty($province)){
			    $data = ResAreaGroup::getAreaByStagePro($stage, $province);
			    $data = $this->handleOutAreaData($province_name, $data);
			    $data['status'] = 1;
			    $return = $data;
		    } else {
			    $return['status'] = 2;//不获取数据
		    }
		    return $this->sendJsonResponse($return);
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500, $e->getMessage() );
	    }
    }

	/**
	 * 根据省份id和已设置区域查找未设置区域
	 *
	 * @return array
	 *
	 * create by qgz 20180730
	 */
    public function handleOutAreaData($province_name, $data){
    	$return = ['name' => $province_name, 'num' => 0, 'city' => ''];
    	$params = [
    		'columns' => 'sProvinceName, sCityName, sCountyName',
		    'conditions' => 'bDelete = 0 and sProvinceName = :sProvinceName:',
		    'bind' => ['sProvinceName' => $province_name]
	    ];
    	$schoolData = XhschoolInfo::find($params)->toArray();
    	if (empty($schoolData)){
		    return $return;
	    }
	    $existArr = $finaArr = [];
	    if (!empty($data)){
		    $existArr = array_column($data, 'districtName');
	    }
	    foreach ($schoolData as $value){
	    	if ($value['sCountyName'] && $value['sCityName']){
			    if (!in_array($value['sCountyName'], $existArr) && !in_array($value['sCityName'].$value['sCountyName'], $finaArr)){
				    $finaArr[] = $value['sCityName'].$value['sCountyName'];
			    }
		    }
	    }
	    if (empty($finaArr)){
		    return $return;
	    }
	    $return['num'] = count($finaArr);
	    $return['city'] = implode('，', $finaArr);
	    return $return;
    }

	/**
	 * 新增区域组页面
	 *
	 *
	 * create by qgz 20180725
	 */
	public function addAreaGroupAction(){
		Assets::select2();
		Assets::easyUI('js/res/addAreaGroupForm.js');
		$this->view->pick('res/addAreaGroupForm');
	}

	/**
	 * 修改区域组页面
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
	 *
	 * create by qgz 20180802
	 */
	public function modifyAreaGroupAction(){
		if (!Power::exist('Res_AreaBookVerList_Edit')) {
			return $this->sendViewError('无修改权限');
		}
		$groupId = $this->request->getQuery('groupId');
		try {
			$data = ResAreaGroup::getGroupInfoById($groupId);
			Assets::select2();
			Assets::easyUI('js/res/modifyAreaGroupForm.js');
			$this->view->pick('res/modifyAreaGroupForm');
			$this->view->setVars([
				'groupId' => $groupId,
				'nameData' => "'".$data['groupName']."'",
				'stageId' => $data['stageType'],
			]);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage());
		}
	}

	/**
	 * 获取区域组基本信息
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180802
	 */
	public function getGroupNameDataAction(){
		$groupId = $this->request->getPost('groupId');
		if (!$groupId){
			return $this->sendErrorResponse(400, '缺少组id');
		}
		try {
			$data = ResAreaGroup::getGroupInfoById($groupId);
			return $this->sendJsonResponse(['name' => $data['groupName'], 'stage' => $data['stageType']]);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 获取区域组学科版本信息
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180802
	 */
	public function getSubVerDataAction(){
		$groupId = $this->request->getPost('groupId');
		$return = [];
		try {
			$data = ResAreaGroup::getSubVerById($groupId);
			if (empty($data)){
				return $this->sendJsonResponse($return);
			}
			$stage = ResAreaGroup::getGroupInfoById($groupId);//学段
			$stage = $stage['stageType'];

			$return = $this->handleSubVerGrade($stage, $data);
			return $this->sendJsonResponse($return);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

    /**
     * 处理学科版本年级数据，格式化成前端可使用的形式
     *
     * @param $stage
     * @param $data
     *
     * @return mixed
     *
     * create by qgz 20180808
     */
	public function handleSubVerGrade($stage, $data){
		$books = new Books();
		$allData = $books->getBookData();
		$allEnum = $this->getEnumTypeList();
		$subject = $this->getSubjectByStageAction(true,$stage,$allData,$allEnum);//学科数据

        $handData1 = $handData2 = $handData3 = [];
		foreach ($data as $value){
			$handData1[$value['subjectId']][$value['textBookVersion']][] = $value['gradeId'];
			unset($value);
		}
		unset($data);
		foreach ($handData1 as $key => $value){
			foreach ($value as $key1 => $value1){
				$handData2[] = [
					'sub' => $key,
					'ver' => $key1,
					'gra' => $value1
				];
			}
			unset($key,$key1,$value,$value1);
		}
		unset($handData1);
		foreach ($handData2 as $key => $value){
			$version = $this->getVersionBySubAction(true,$stage,$value['sub'],$allData,$allEnum);
			$grade = $this->getGradeBySubVerAction(true,$stage,$value['ver'],$value['sub'],$allData,$allEnum);
			$handData3[$key]['version'] = $version;
			$handData3[$key]['empty_ver'] = empty($version) ? 0 : 1;
			$handData3[$key]['grade'] = $grade;
			$handData3[$key]['empty_gra'] = empty($grade) ? 0 : 1;
			$handData3[$key]['subVerData'] = $value;
			unset($key,$value);
		}
		unset($handData2);
		$return['subject'] = $subject;
		$return['empty_sub'] = empty($subject) ? 0 : 1;
		$return['data'] = $handData3;
		return $return;
	}

	/**
	 * 保存区域组名称信息
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180730
	 */
	public function saveGroupInfoAction(){
		$name = $this->request->getPost('name');
		$stage = $this->request->getPost('stage');
		$groupId = $this->request->getPost('groupId');
		try {
			if (!empty($stage) && !empty($name)){
				$params = [
					'groupName' => $name,
					'stageType' => $stage,
					'userId' => User::getId()
				];
				$return = ResAreaGroup::saveGroupInfo($params, $groupId);
				return $this->sendJsonResponse($return);
			} else {
				return $this->sendErrorResponse( 400, '请填写完整信息');
			}
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 根据学段获取学科信息
	 *
	 * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180730
	 */
	public function getSubjectByStageAction($returnArr=false,$stage=null,$allData=[],$allEnum=[]){
		if (!$returnArr){//如果有传数据则直接用
			$stage = $this->request->getPost('stage');
			$books = new Books();
			$allData = $books->getBookData();
			$allEnum = $this->getEnumTypeList();
		}

		$data = [];
		foreach ($allData as $value){
			switch ($stage){
				case 1:
					if ($value['gradeId'] < 70 && !in_array($value['subjectId'], $data)){
						$data[] = $value['subjectId'];
					}
					break;
				case 2:
					if ($value['gradeId'] > 70 && $value['gradeId'] < 100 && !in_array($value['subjectId'], $data)){
						$data[] = $value['subjectId'];
					}
					break;
				case 3:
					if ($value['gradeId'] >= 100 && !in_array($value['subjectId'], $data)){
						$data[] = $value['subjectId'];
					}
					break;
			}
		}
		if (!$returnArr){
			$return[] = ['id' => '', 'text' => ''];
		}else{
			$return = [];
		}

		if (!empty($data)){
			foreach ($data as $id){
				$return[] = ['id' => $id, 'text' => $allEnum['subject'][$id]];
			}
		}

		if (!$returnArr){
			return $this->sendJsonResponse($return);
		} else {
			return $return;
		}
	}

    /**
     * 根据学科和学段获取教材版本
     *
     * @param bool $returnArr
     * @param null $stage
     * @param null $subject
     * @param array $allData
     * @param array $allEnum
     *
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180802
     */
	public function getVersionBySubAction($returnArr=false,$stage=null,$subject=null,$allData=[],$allEnum=[]){
		if (!$returnArr) {//如果有传数据则直接用
			$stage = $this->request->getPost('stage');
			$subject = $this->request->getPost('subject');
			$books = new Books();
			$allData = $books->getBookData();
			$allEnum = $this->getEnumTypeList();
		}
		$data = [];
		foreach ($allData as $value){
			switch ($stage){
				case 1:
					if ($value['gradeId'] < 70 && !in_array($value['textBookVersion'], $data) && $value['subjectId'] == $subject ){
						$data[] = $value['textBookVersion'];
					}
					break;
				case 2:
					if ($value['gradeId'] > 70 && $value['gradeId'] < 100 && !in_array($value['textBookVersion'], $data) && $value['subjectId'] == $subject){
						$data[] = $value['textBookVersion'];
					}
					break;
				case 3:
					if ($value['gradeId'] >= 100 && !in_array($value['textBookVersion'], $data) && $value['subjectId'] == $subject){
						$data[] = $value['textBookVersion'];
					}
					break;
			}
		}
		if ($returnArr){
			$return = [];
		}else{
			$return[] = ['id' => '', 'text' => ''];
		}
		$name = $exist = [];
		if (!empty($data)){
			foreach ($data as $id){
				if (in_array($allEnum['book'][$id], $name)){
					$exist[] = $allEnum['book'][$id];
				} else {
					$name[] = $allEnum['book'][$id];
				}
			}
			foreach ($data as $id){
				if (in_array($allEnum['book'][$id], $exist)){
					$return[] = ['id' => $id, 'text' => $allEnum['book'][$id].'_'.$id];
				} else {
					$return[] = ['id' => $id, 'text' => $allEnum['book'][$id]];
				}
			}
		}
		if (!$returnArr) {
			return $this->sendJsonResponse($return);
		} else {
			return $return;
		}
	}

	/**
	 * 根据教材版本和学科获取年级数据
	 *
	 * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180731
	 */
	public function getGradeBySubVerAction($returnArr=false,$stage=null,$version=null,$subject=null,$allData=[],$allEnum=[]){
	    if (!$returnArr){//如果有传数据则直接用
			$version = $this->request->getPost('version');
			$subject = $this->request->getPost('subject');
			$stage = $this->request->getPost('stage');
			$books = new Books();
			$allData = $books->getBookData();
			$allEnum = $this->getEnumTypeList();
		}

		$data = [];
		foreach ($allData as $value){
			if ($value['subjectId'] == $subject && $value['textBookVersion'] == $version && !array_key_exists($value['gradeId'], $data)){
				switch ($stage){
					case 1:
						if ($value['gradeId'] < 70 ){
							$data[$value['gradeId']] = $allEnum['grade'][$value['gradeId']];
						}
						break;
					case 2:
						if ($value['gradeId'] > 70 && $value['gradeId'] < 100){
							$data[$value['gradeId']] = $allEnum['grade'][$value['gradeId']];
						}
						break;
					case 3:
						if ($value['gradeId'] >= 100 ){
							$data[$value['gradeId']] = $allEnum['grade'][$value['gradeId']];
						}
						break;
				}
			}
		}
		if (!$returnArr){
			return $this->sendJsonResponse($data);
		}else{
			return $data;
		}
	}

	/**
	 * 保存区域组年级、学科、教材关系数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180731
	 */
	public function saveSubjectVersionAction(){
		$postData = $this->request->getPost();
		$isExist = [];
		if (!$postData['groupId']){
			return $this->sendErrorResponse(400, '缺少区域组id');
		}
		$userId = User::getId();
		$params = [
			'groupId' => $postData['groupId'],
			'userId' => $userId,
			'groupTextBookInfoDTOList' => []
		];
		$verData = [];
		foreach ($postData['data'] as $value){
			$check = $this->checkData($value);
			if (!$check['status']){
				return $this->sendErrorResponse(400, $check['msg']);
			}
			if (!isset($value['subjectId']) || (empty($value['subjectId']) && $value['subjectId'] != 0)){//没选择的不保存
				continue;
			}
			if (array_key_exists($value['subjectId'], $isExist) && in_array($value['versionId'], $isExist[$value['subjectId']])){
				return $this->sendErrorResponse(400, '有相同学科版本，请重新选择');
			}
			if (isset($value['versionId'])){
				$isExist[$value['subjectId']][] = $value['versionId'];
			}
			if (isset($value['grade'])){
				foreach ($value['grade'] as $item){
					$verData[] = [
						'gradeId' => $item,
						'subjectId' => $value['subjectId'],
						'textBookVersion' => $value['versionId']
					];
				}
			}
		}
		$params['groupTextBookInfoDTOList'] = $verData;
		try {
			ResAreaGroup::saveSubjectVersion($params);
			return $this->sendSuccessResponse('成功');
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 一键复制保存数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180803
	 */
	public function copyCreateGroupAction(){
		$postData = $this->request->getPost();
		$isExist = [];
		if (!$postData['stageId']){
			return $this->sendErrorResponse(400, '缺少学段id');
		}
		if (empty($postData['groupName'] && $postData['groupName'] !== 0 && $postData['groupName'] !== '0')){
			return $this->sendErrorResponse(400, '请填写名称');
		}
		if (empty($postData['stageId'] && $postData['stageId'] !== 0 && $postData['stageId'] !== '0')){
			return $this->sendErrorResponse(400, '学科id为空');
		}
		$userId = User::getId();

		try {
			$params_1 = [
				'groupName' => $postData['groupName'],
				'stageType' => $postData['stageId'],
				'userId' => $userId
			];
			$return = ResAreaGroup::saveGroupInfo($params_1);//创建区域组
			if ($return['type'] == 1){
				return $this->sendErrorResponse(400, $return['msg']);
			}
			if ($return['type'] == 2 && !$return['groupId']){
				return $this->sendErrorResponse(400, '创建区域组id为空');
			}
			$params_2 = [
				'groupId' => $return['groupId'],
				'userId' => $userId,
				'groupTextBookInfoDTOList' => []
			];
			$verData = [];
			foreach ($postData['data'] as $value){
				$check = $this->checkData($value);
				if (!$check['status']){
					return $this->sendErrorResponse(400, $check['msg']);
				}
				if (!isset($value['subjectId']) || (empty($value['subjectId']) && $value['subjectId'] != 0)){//没选择的不保存
					continue;
				}
				if (array_key_exists($value['subjectId'], $isExist) && in_array($value['versionId'], $isExist[$value['subjectId']])){
					return $this->sendErrorResponse(400, '有相同学科版本，请重新选择');
				}
				if (isset($value['versionId'])){
					$isExist[$value['subjectId']][] = $value['versionId'];
				}
				if (isset($value['grade'])){
					foreach ($value['grade'] as $item){
						$verData[] = [
							'gradeId' => $item,
							'subjectId' => $value['subjectId'],
							'textBookVersion' => $value['versionId'],
						];
					}
				}
			}
			$params_2['groupTextBookInfoDTOList'] = $verData;
			ResAreaGroup::saveSubjectVersion($params_2);//绑定学科版本关系
			return $this->sendSuccessResponse('成功');
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 检测数据正确性
	 *
	 * @return array
	 *
	 * create by qgz 20180731
	 */
	public function checkData($value,$isBlack=false){
		$return = ['status' => true, 'msg' => ''];
		if (isset($value['subjectId']) && (!empty($value['subjectId']) || $value['subjectId'] === 0 || $value['subjectId'] === 0)){//存在
			if (!isset($value['versionId']) || !isset($value['grade'])){
				if(!$isBlack){
					return ['status' => false, 'msg' => '请选择版本和年级'];
				}
			}
			if (empty($value['versionId']) && $value['versionId'] !== 0 && $value['versionId'] !== '0'){
				return ['status' => false, 'msg' => '版本不能为空'];
			}
			if (!$isBlack && empty($value['grade'])){
				return ['status' => false, 'msg' => '年级不能为空'];
			}
		}
		return $return;
	}

	/**
	 * 保存黑白名单
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180809
	 */
	public function saveWhiteAndBlackDataAction(){
		$postData = $this->request->getPost();
		$isExist = [];
		if (!$postData['groupId']){
			return $this->sendErrorResponse(400, '缺少区域组id');
		}
		if (isset($postData['white'])){
			foreach ($postData['white'] as $value){//检测白名单选择数据是否重复和空
				$check = $this->checkData($value);
				if (!$check['status']){
					return $this->sendErrorResponse(400, $check['msg']);
				}
				if (empty($value['subjectId']) && ($value['subjectId'] != 0 || $value['subjectId'] === '')){//没选择的不保存
					continue;
				}
			}
			$allData = array_merge($postData['data'], $postData['white']);
		} else {
			$allData = $postData['data'];
		}

		foreach ($allData as $value){//检查数据格式是否正确,
			$check = $this->checkData($value,true);
			if (!$check['status']){
				return $this->sendErrorResponse(400, $check['msg']);
			}
			if (empty($value['subjectId']) && ($value['subjectId'] != 0 || $value['subjectId'] === '')){//没选择的不保存
				continue;
			}
			if (array_key_exists($value['subjectId'], $isExist) && in_array($value['versionId'], $isExist[$value['subjectId']])){
				return $this->sendErrorResponse(400, '有相同学科版本，请重新选择');
			}
			$isExist[$value['subjectId']][] = $value['versionId'];
		}

		$userId = User::getId();
		$whiteParams = $blackParams = $notBlackArr = [];
		if (isset($postData['white'])){
			foreach ($postData['white'] as $value){//新增白名单
				if (isset($value['grade'])){
					foreach ($value['grade'] as $item){
						$whiteParams[] = [
							'gradeId' => $item,
							'groupId' => $postData['groupId'],
							'subjectId' => $value['subjectId'],
							'textBookVersion' => $value['versionId'],
							'userId' => $userId,
							'schoolId' => $postData['schoolId']
						];
					}
				}
			}
		}
		foreach ($postData['data'] as $value){//组内勾选的进白名单
			if (isset($value['grade']['white'])){
				foreach ($value['grade']['white'] as $item){
					$whiteParams[] = [
						'gradeId' => $item,
						'groupId' => $postData['groupId'],
						'subjectId' => $value['subjectId'],
						'textBookVersion' => $value['versionId'],
						'userId' => $userId,
						'schoolId' => $postData['schoolId']
					];
				}
			}
//			if (isset($value['grade']['data'])){
//				foreach ($value['grade']['data'] as $gradeId){
//					$notBlackArr[] = $value['subjectId'].'+'.$value['versionId'].'+'.$gradeId;//不是黑名单的数据
//				}
//			}
		}
		try {
//			$groupExist = [];
//			$data = ResAreaGroup::getSubVerById($postData['groupId']);
//			if (empty($data)){
//				return $this->sendJsonResponse([]);
//			}
//			$stage = ResAreaGroup::getGroupInfoById($postData['groupId']);//学段
//			$stage = $stage['stageType'];
//			$groupData = $this->handleSubVerGrade($stage, $data);//群组全部数据
//			foreach ($groupData['data'] as $key => $value){
//				if (isset($value['subVerData']) && isset($value['subVerData']['gra']) && !empty($value['subVerData']['gra'])){
//					foreach ($value['subVerData']['gra'] as $gradeId){
//						$groupExist[] = $value['subVerData']['sub'].'+'.$value['subVerData']['ver'].'+'.$gradeId;
//					}
//				}
//			}
//			if (!empty($groupExist)){
//				foreach ($groupExist as $idStr){
//					if (!in_array($idStr,$notBlackArr)){//群组里数据减去前端传来的数据差集进黑名单
//						$idArr = explode('+', $idStr);
//						$blackParams[] = [
//							'gradeId' => $idArr[2],
//							'groupId' => $postData['groupId'],
//							'subjectId' => $idArr[0],
//							'textBookVersion' => $idArr[1],
//							'userId' => $userId,
//							'schoolId' => $postData['schoolId']
//						];
//					}
//				}
//			}

            if (isset($postData['blackArr']) && $postData['blackArr']) {//黑名单数据
                foreach ($postData['blackArr'] as $blackData) {
                    $blackParams[] = [
                        'gradeId' => $blackData['grade'],
                        'groupId' => $postData['groupId'],
                        'subjectId' => $blackData['subject'],
                        'textBookVersion' => $blackData['version'],
                        'userId' => $userId,
                        'schoolId' => $postData['schoolId']
                    ];
                }
            }

			if (empty($blackParams)){//没有黑名单数据传0值
				$blackParams = [[
					'gradeId' => 0,
					'groupId' => $postData['groupId'],
					'subjectId' => 0,
					'textBookVersion' => 0,
					'userId' => $userId,
					'schoolId' => $postData['schoolId']
				]];
			}
			if (empty($whiteParams)){//没有白名单数据传0值
				$whiteParams = [[
					'gradeId' => 0,
					'groupId' => $postData['groupId'],
					'subjectId' => 0,
					'textBookVersion' => 0,
					'userId' => $userId,
					'schoolId' => $postData['schoolId']
				]];
			}
			ResAreaGroup::saveBlackData($blackParams);//保存黑名单
			ResAreaGroup::saveWhiteData($whiteParams);//保存白名单
			return $this->sendSuccessResponse('成功');
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 设置添加省份页面
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180806
	 */
	public function setProvPageAction(){
		Assets::easyUI('js/res/addAreaProvForm.js');
		$this->view->pick('res/addAreaProvForm');
		$existProvArr = $this->request->getQuery('existProv');
		try {
			$areaObj = new Area();
			$allPro = $areaObj->getAllProvinces(true);
			$this->view->setVars([
				'provIds' => json_encode($allPro),
				'existIds' => $existProvArr ? json_encode(explode(',', $existProvArr)) : json_encode([])
			]);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 获取地区信息树
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180807
	 */
	public function getAreaDataByProvAction(){
		$stageId = $this->request->getPost('stageId');
		$provId = $this->request->getPost('provId');
		$groupId = $this->request->getPost('groupId');
		try {
			$existDataArr = $return = $existCityArr = $checkCityArr = $groupData = $districtIds = [];
			if ($groupId){
				$groupData =  ResAreaGroup::getAreaDataById($groupId);
			}
			$districtIds = array_unique(array_column($groupData,'districtId'));

			if (!empty($stageId) && !empty($provId)){
				$existData =  ResAreaGroup::getAreaByStagePro($stageId, $provId);
				if (!empty($existData)){
					$existDataArr = array_column($existData,'districtId');
				}
			}
			$areaObj = new Area((int)$provId);
			$return['provId'] = $provId;
			$return['provName'] = $areaObj->getCurrent();
			$return['cityArr'] = [];
			$isCQ = false;
			if ($provId == 500000) {//重庆市的话加上丰都县，姚超让加的
                $isCQ = true;
            }
			$allCity = $areaObj->getCity();
			foreach ($allCity as $key => $value){
				$cityArr['cityId'] = $key;
				$cityArr['cityName'] = $value;
				$cityArr['distArr'] = $distArr = $existDistArr = $checkDistArr = [];

				$distObj = new Area((int)$key);
				$allDist = $distObj->getDistrict();
				if ($isCQ) {
                    $allDist[500230] = '丰都县';
                }
				foreach ($allDist as $item => $val){
					if (in_array($item, $existDataArr)){
						if (in_array($item, $districtIds)){
							$distCheck = true;
							$distExist = false;
							$checkDistArr[] = $item;
						} else {
							$distCheck = false;
							$distExist = true;
							$existDistArr[] = $item;
						}
					} else {
						$distCheck = false;
						$distExist = false;
					}
					$distArr[] = ['distId' => $item, 'distName' => $val, 'isExist' => $distExist, 'isChecked' => $distCheck];
				}
				$cityArr['isAllExist'] = (count($existDistArr) == count($allDist)) && count($allDist) != 0 ? true : false;
				$cityArr['isAllChecked'] = (count($allDist) - count($existDistArr) == count($checkDistArr)) && count($checkDistArr) != 0 ? true : false;
				if ($cityArr['isAllExist']){
					$existCityArr[] = $key;
				}
				if ($cityArr['isAllChecked']){
					$checkCityArr[] = $key;
				}
				$cityArr['distArr'] = $distArr;
				$return['cityArr'][] = $cityArr;
			}
			$return['isAllExist'] = (count($existCityArr) == count($allCity)) && count($allCity) != 0 ? true : false;
			$return['isAllChecked'] = (count($allCity) - count($existCityArr) == count($checkCityArr)) && count($checkCityArr) != 0 ? true : false;
			return $this->sendJsonResponse($return);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 保存地域数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180807
	 */
	public function saveAreaDataAction(){
		$postData = $this->request->getPost();
		if (!$postData['groupId']){
			return $this->sendErrorResponse(400, '缺少群组id');
		}
		$return['groupId'] = $postData['groupId'];
		$return['userId'] = User::getId();
		$return['groupDistrictInfoDTOList'] = [];
		if (!isset($postData['data']) || empty($postData['data'])){
			try {
				ResAreaGroup::saveAreaData($return);//绑定组和区域关系
				return $this->sendSuccessResponse('成功');
			} catch ( \Exception $e ) {
				return $this->sendErrorResponse( 500, $e->getMessage() );
			}
		}
		$allDistArr = [];
		foreach ($postData['data'] as $value){
			if (isset($value['dist']) && !empty($value['dist'])){
				$allDistArr = array_merge($allDistArr, $value['dist']);
			}
		}
		$allDistArr = array_unique($allDistArr);
		if (empty($allDistArr)){
			try {
				ResAreaGroup::saveAreaData($return);//绑定组和区域关系
				return $this->sendSuccessResponse('成功');
			} catch ( \Exception $e ) {
				return $this->sendErrorResponse( 500, $e->getMessage() );
			}
		}
		try {
			$areaData = [];
			foreach ($allDistArr as $code){
				$areaObj = new Area((int)$code);
				$provArr = $areaObj->getProvByDist($code, true);
				$cityArr = $areaObj->getCityByDist($code, true);
				$data['provinceId'] = $provArr['provId'];
				$data['provinceName'] = $provArr['provName'];
				$data['cityId'] = $cityArr['cityId'];
				$data['cityName'] = $cityArr['cityName'];
				$data['districtId'] = $code;
				$data['districtName'] = $areaObj->getCurrent();
				$areaData[] = $data;
			}
			$return['groupDistrictInfoDTOList'] = $areaData;
			ResAreaGroup::saveAreaData($return);//绑定组和区域关系
			return $this->sendSuccessResponse('成功');
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 根据群组id获取区域数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180807
	 */
	public function getAreaDataByGroupIdAction(){
		$groupId = $this->request->getPost('groupId');
		$stageId = $this->request->getPost('stageId');
		if (!$groupId || !$stageId){
			return $this->sendErrorResponse(400, '缺少群组id或学段id');
		}
		try {
			$existData =  ResAreaGroup::getAreaDataById($groupId);
			if (empty($existData)){
				return $this->sendJsonResponse([]);
			}
			$districtIds = array_unique(array_column($existData,'districtId'));

			$provIds = array_values(array_unique(array_column($existData,'provinceId')));
			$return = $fina = [];
			foreach ($provIds as $prov_id){
                $isCQ = false;
                if ($prov_id == 500000) {//重庆市的话加上丰都县，姚超让加的
                    $isCQ = true;
                }
				$existCityArr = $checkCityArr = [];
				$haveExist =  ResAreaGroup::getAreaByStagePro($stageId, $prov_id);
				$haveExist = !empty($haveExist) ? array_column($haveExist,'districtId') : [];

				$areaObj = new Area((int)$prov_id);
				$return['provId'] = $prov_id;
				$return['provName'] = $areaObj->getCurrent();
				$return['cityArr'] = [];

				$allCity = $areaObj->getCity();
				foreach ($allCity as $key => $value){
					$cityArr['cityId'] = $key;
					$cityArr['cityName'] = $value;
					$cityArr['distArr'] = $distArr = $existDistArr = $checkDistArr = [];

					$distObj = new Area((int)$key);
					$allDist = $distObj->getDistrict();
                    if ($isCQ) {
                        $allDist[500230] = '丰都县';
                    }
					foreach ($allDist as $item => $val){
						$distExist = $distChecked = false;
						if (in_array($item, $districtIds)){
							$distChecked = true;
							$checkDistArr[] = $item;
						} else {
							if (in_array($item, $haveExist)){
								$distExist = true;
								$existDistArr[] = $item;
							}
						}
						$distArr[] = ['distId' => $item, 'distName' => $val, 'isChecked' => $distChecked, 'isExist' => $distExist];
					}
					$cityArr['isAllExist'] = (count($existDistArr) == count($allDist)) && (count($existDistArr) != 0) ? true : false;//市，都存在
					$cityArr['isAllChecked'] = (count($allDist) - count($existDistArr) == count($checkDistArr)) && (count($checkDistArr) != 0) ? true : false;//市，都选中
					$cityArr['distArr'] = $distArr;
					$return['cityArr'][] = $cityArr;
					if ($cityArr['isAllExist']){
						$existCityArr[] = $key;
					}
					if ($cityArr['isAllChecked']){
						$checkCityArr[] = $key;
					}
				}
				$return['isAllExist'] = (count($existCityArr) == count($allCity)) && (count($allCity) != 0) ? true : false;//省，都存在
				$return['isAllChecked'] = (count($allCity) - count($existCityArr) == count($checkCityArr)) && (count($checkCityArr) != 0) ? true : false;//省，都选中
				$fina[] = $return;
			}
			return $this->sendJsonResponse($fina);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 获取编辑学校教材版本全部数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180809
	 */
	public function getAllDataAction(){
		$groupId = $this->request->getPost('groupId');
		$schoolId = $this->request->getPost('schoolId');
		$stageId = $this->request->getPost('stageId');
		$groupExist = [];
		try {
//			$data = ResAreaGroup::getSubVerById($groupId);
            $data = ResAreaGroup::getSchoolTextBook($schoolId);
			if (empty($data['groupTextBookResponseList'])){
				return $this->sendJsonResponse([]);
			}
			$stage = ResAreaGroup::getGroupInfoById($groupId);//学段
			$stage = $stage['stageType'];
			$groupData = $this->handleSubVerGrade($stage, $data['groupTextBookResponseList']);//群组数据
			foreach ($groupData['data'] as $key => &$value){
				$groupExist[] = $value['subVerData']['sub'].'+'.$value['subVerData']['ver'];
				$value['subVerData']['gra_data']['data'] = $value['subVerData']['gra'];
				$value['subVerData']['gra_data']['white'] = [];
				unset($value['subVerData']['gra']);
			}
			unset($value);
			$groupData['data'] = array_values($groupData['data']);
			$whiteData = [];
			//黑名单数据,移除
			if (!empty($data['blackResponseList'])){
				foreach ($groupData['data'] as $key => &$value){
					foreach ($data['blackResponseList'] as $item){
						if ($item['subjectId'] == $value['subVerData']['sub'] && $item['textBookVersion'] == $value['subVerData']['ver']){
							$value['subVerData']['gra_data']['data'] = array_values(array_diff($value['subVerData']['gra_data']['data'], [$item['gradeId']]));//移除黑名单数据
                            $value['subVerData']['gra_data']['black'][] = $item['gradeId'];//组内黑名单
						}
					}
				}
				unset($value);
			}
			//白名单数据
			if (!empty($data['whiteResponseList'])){
				$whiteData = $this->handleSubVerGrade($stageId, $data['whiteResponseList']);
				foreach ($whiteData['data'] as $key => &$value) {
                    //在白名单数据中移除掉在群组中的白名单数据
					if (in_array($value['subVerData']['sub'].'+'.$value['subVerData']['ver'], $groupExist)){
						foreach ($groupData['data'] as $k => &$v){
							if ($value['subVerData']['sub'].'+'.$value['subVerData']['ver'] == $v['subVerData']['sub'].'+'.$v['subVerData']['ver']){
								$v['subVerData']['gra_data']['white'] = $value['subVerData']['gra'];
								unset($whiteData['data'][$key]);
							}
						}
						unset($v);
					}
					//加上黑名单数据
                    foreach ($data['blackResponseList'] as $item){
                        if ($item['subjectId'] == $value['subVerData']['sub'] && $item['textBookVersion'] == $value['subVerData']['ver']){
                            $value['subVerData']['black'][] = $item['gradeId'];//白名单内的黑名单数据
                        }
                    }
				}
				unset($value);
			}
			$return['data'] = $groupData;
			$return['white'] = $whiteData;
			return $this->sendJsonResponse($return);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 添加年级页
	 *
	 *
	 * create by qgz 20180808
	 */
	public function setGradePageAction(){
		Assets::easyUI('js/res/addGradeForm.js');
		$this->view->pick('res/addGradeForm');
		$groupId = $this->request->getQuery('groupId');
		$stage = $this->request->getQuery('stage');
		$sub = $this->request->getQuery('sub');
		$ver = $this->request->getQuery('ver');
		$id = $this->request->getQuery('id');
		$length = $this->request->getQuery('lengthData');
		$type = $this->request->getQuery('type');
		$grade = $this->request->getQuery('grade');
		$grade = explode(',', $grade);

		$outIds = [];
		$books = new Books();
		$allData = $books->getBookData();
		$allEnum = $this->getEnumTypeList();
		$allGrade = $this->getGradeBySubVerAction(true,$stage,$ver,$sub,$allData,$allEnum);
		if (!empty($allGrade)){
			foreach ($allGrade as $key => $value){
				if (!in_array($key, $grade)){
					$outIds[$key] = $value;
				}
			}
		}
		$this->view->setVars([
			'id' => $id,
			'type' => $type,
			'length' => $length,
			'outIds' => json_encode($outIds),
			'groupId' => $groupId,
			'subject' => $sub,
			'version' => $ver,
		]);
	}

	/**
	 * 检查年级是否在群组内
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180814
	 */
	public function checkGradeInGroupAction(){
		$groupId = $this->request->getPost('groupId');
		$subject = $this->request->getPost('subject');
		$version = $this->request->getPost('version');
		$grade = $this->request->getPost('grade');
		$return = ['isInGroup' => 0];
		try {
			$data = ResAreaGroup::getSubVerById($groupId);
			if (empty($data)){
				return $this->sendJsonResponse($return);
			}
			foreach ($data as $value){
				if ($value['subjectId'] == $subject && $value['textBookVersion'] == $version && $value['gradeId'] == $grade){
					$return = ['isInGroup' => 1];
				}
			}
			return $this->sendJsonResponse($return);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

    /**
     * 排期计划汇总页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181012
     */
	public function schedulePlanAction()
    {
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('res/schedulePlan');
        Main::showNavPosition();
        Assets::easyUI('js/res/schedulePlan.js');
        if (!UserPower::checkUserPower('Res_SchedulePlan')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        $listSearchArr = $listButtonArr = [];
        $existPlanEnum = $this->registerEnum['referenceApply']['iExistPlan'];
        unset($existPlanEnum[0]);
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'search_status',
            'data' => ['' => '-申请状态-'] + $this->existPlanStatus, 'style' => 'width: 90px;'
        ];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'search_date', 'style' => 'width: 100px;'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'plan_startTime'];
        $listSearchArr[] = ['label' => ' ~ ', 'type' => 'text', 'id' => 'plan_endTime'];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'search_demand',
            'data' => ['' => '-需求录入-'] + $this->registerEnum['referenceApply']['iDemandStatus'], 'style' => 'width: 90px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'search_book',
            'data' => ['' => '-书本状态-'] + [1 => '完成', 2 => '未完成'], 'style' => 'width: 90px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'search_bookSubject', 'multiple' => true,
            'data' => ['' => '-书本科目-'] + $this->getBookSubjectEnum('subject'),'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'search_bookClass', 'multiple' => true,
            'data' => ['' => '-书本年级-'] + $this->getBookSubjectEnum('grade'),'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'search_newApply',
            'data' => ['' => '-来源-'] + [1 => '外部', 2 => '内部'], 'style' => 'width: 70px;'
        ];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        if (Power::exist('Res_SchedulePlan_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '添加', 'plain' => 'true', 'icon' => 'fa-plus'];
        }
        $listButtonArr[] = ['id' => 'bt_list_demandStatus', 'text' => '需求状态', 'plain' => 'true', 'icon' => 'fa-bookmark-o'];
//        $listButtonArr[] = ['id' => 'bt_list_bookStatus', 'text' => '书本状态', 'plain' => 'true', 'icon' => 'fa-book'];
        //$listButtonArr[] = ['id' => 'bt_list_power', 'text' => '查看权限', 'plain' => 'true', 'icon' => 'fa-eye'];
        $listButtonArr[] = ['id' => 'bt_list_refresh', 'text' => '刷新书本状态', 'plain' => 'true', 'icon' => 'fa-refresh'];
        if (Power::exist('Res_SchedulePlan_Summary')) {
            $listButtonArr[] = ['id' => 'bt_list_planSummary', 'text' => '排期查询', 'plain' => 'true', 'icon' => 'fa-sliders'];
        }
        $power['add'] = false;
        if (Power::exist('Res_SchedulePlan_Add')) {
            $power['add'] = true;
        }
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHRes_SchedulePlan', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'power' => $power,
        ]);
    }

    /**
     * 获取排期计划数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by qgz 20181012
     */
    public function getSchedulePlanDataAction()
    {
        $postData = $this->request->getPost();
        $search = [];
        $condition = " A.bDelete = 0 ";
        if (isset($postData['search'])) {
            $search = $postData['search'];
        }
        //搜索书名或书id
        if (isset($search['vague']) && $search['vague']) {
            $condition .= " and (A.iBookId like '%{$search['vague']}%' or A.sBookName like '%{$search['vague']}%')";
        }
        //搜索录入状态
        if (isset($search['demand_status']) && $search['demand_status'] !== '') {
            $condition .= " and A.iDemandStatus = " . $search['demand_status'];
        }
        //搜索内外部
        if (isset($search['new_apply']) && in_array($search['new_apply'], [1, 2])) {
            $outIdArr = $this->getOutIdArr();//获取外部申请书idArr
            if ($search['new_apply'] == 1) {//外部
                if ($outIdArr) {
                    $outIdArr = implode("','", $outIdArr);
                    $outIdArr = "'" . $outIdArr . "'";
                    $condition .= " and A.iBookId in ({$outIdArr})";
                } else {
                    $condition .= " and A.iBookId in ('-100')";
                }
            } else {//内部
                if ($outIdArr) {
                    $outIdArr = implode("','", $outIdArr);
                    $outIdArr = "'" . $outIdArr . "'";
                    $condition .= " and A.iBookId not in ({$outIdArr})";
                }
            }
        }
        //搜索书本状态
        if (isset($search['book_status']) && $search['book_status'] !== '') {
            if ($search['book_status'] == 1) {
                $condition .= " and B.iStatus = 3 ";//书本状态是完成
            } else {
                $condition .= " and B.iStatus != 3 ";//未完成
            }
        }
        //学科科目扩展权限
        $subjectPower = Power::getExtraPower('resManage','schedulePlanSubject');
//        $gradePower = Power::getExtraPower('resManage','schedulePlanGrade');
        if ($subjectPower) {
            if ($subjectPower !== true) {
                $subjectPower = implode("','", $subjectPower);
                $subjectPower = "'" . $subjectPower . "'";
                $condition .= " and B.iBookSubject in ({$subjectPower}) ";
            }
        } else {
            return $this->sendJsonResponse(['rows' => [], 'total' => 0]);
        }
//        if ($gradePower) {
//            if ($gradePower !== true) {
//                $gradePower = implode("','", $gradePower);
//                $gradePower = "'" . $gradePower . "'";
//                $condition .= " and B.iBookClass in ({$gradePower}) ";
//            }
//        } else {
//            return $this->sendJsonResponse(['rows' => [], 'total' => 0]);
//        }
//        //科目
//        if (isset($search['book_subject']) && $search['book_subject'] !== '') {
//            $condition .= " and B.iBookSubject = " . $search['book_subject'];
//        }
//        //年级
//        if (isset($search['book_class']) && $search['book_class'] !== '') {
//            $condition .= " and B.iBookClass = " . $search['book_class'];
//        }

        //科目
        if (isset($search['book_subject']) && $search['book_subject'] !== '' && $search['book_subject'] !== null) {
            $bookSubjectStatus = $this->handleSearchStatus($search['book_subject']);
            if ($bookSubjectStatus) {
                $condition .= " AND B.iBookSubject in ($bookSubjectStatus)";
            }
        }
        //年级
        if (isset($search['book_class']) && $search['book_class'] !== '' && $search['book_class'] !== null) {
            $bookClassStatus = $this->handleSearchStatus($search['book_class']);
            if ($bookClassStatus) {
                $condition .= " AND B.iBookClass in ($bookClassStatus)";
            }
        }
        //学校权限,仅从教辅申请那申请的有学校，其他无学校的排期不予展示（true时全展示）
        $powerIds = School::getPower();
        if ($powerIds !== true) {
            if (!$powerIds) {
                return $this->sendJsonResponse(['rows' => [], 'total' => 0]);
            }
            $applyIdArr = XhresReferenceApply::find([
                'columns' => 'iId',
                'conditions' => "bDelete = 0 and iSchoolId in ({idArr:array})",
                'bind' => ['idArr' => $powerIds]
            ])->toArray();
            if (!$applyIdArr) {
                return $this->sendJsonResponse(['rows' => [], 'total' => 0]);
            }
            $applyIdArr = implode(',', array_values(array_unique(array_filter(array_column($applyIdArr, 'iId')))));
            $condition .= " AND A.iAddType = 1 AND iApplyId IN ({$applyIdArr})";
        }
        $outBookCondition = '';
        if (isset($search['status']) && $search['status'] !== '') {//选择了申请状态
            if ($search['status'] == 1) {//已申请
                //选择了时间类型
                if (isset($search['plan_date']) && $search['plan_date'] !== '') {
                    $startTime = isset($search['startTime']) && $search['startTime'] ? $search['startTime'] : '';
                    $endTime = isset($search['endTime']) && $search['endTime'] ? $search['endTime'] : '';
                    switch ($search['plan_date']) {
                        case 0:
                            $dateStr = 'sStartDate';
                            break;
                        case 1:
                            $dateStr = 'sEndDate';
                            break;
                        case 2:
                            $dateStr = 'sRealStartDate';
                            break;
                        case 3:
                            $dateStr = 'sRealEndDate';
                            break;
                        case 4:
                            $dateStr1 = 'sStartDate';
                            $dateStr2 = 'sEndDate';
                            break;
                        case 5:
                            $dateStr1 = 'sRealStartDate';
                            $dateStr2 = 'sRealEndDate';
                            break;
                    }
                    if (in_array($search['plan_date'], [4, 5])) {
                        if ($startTime){
                            $condition .= " AND A.".$dateStr1." >= '{$startTime}'";
                        }
                        if ($endTime){
                            $condition .= " AND A.".$dateStr2." <= '{$endTime}"." 23:59:59"."'";
                        }
                    } else {
                        if ($startTime){
                            $condition .= " AND A.".$dateStr." >= '{$startTime}'";
                        }
                        if ($endTime){
                            $condition .= " AND A.".$dateStr." <= '{$endTime}"." 23:59:59"."'";
                        }
                    }
                }
            } else {//未申请
                if (!$search['startTime'] && !$search['endTime']) {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                }
                $outBookCondition = " WHERE iBookId NOT IN (
                        SELECT
                            iBookId
                        FROM
                            XHRes_ReferencePlan
                        WHERE bDelete = 0 ";
                $startTime = isset($search['startTime']) && $search['startTime'] ? $search['startTime'] : '';
                $endTime = isset($search['endTime']) && $search['endTime'] ? $search['endTime'] : '';
                switch ($search['plan_date']) {
                    case 0:
                        $dateStr = 'sStartDate';
                        break;
                    case 1:
                        $dateStr = 'sEndDate';
                        break;
                    case 2:
                        $dateStr = 'sRealStartDate';
                        break;
                    case 3:
                        $dateStr = 'sRealEndDate';
                        break;
                    case 4:
                        $dateStr1 = 'sStartDate';
                        $dateStr2 = 'sEndDate';
                        break;
                    case 5:
                        $dateStr1 = 'sRealStartDate';
                        $dateStr2 = 'sRealEndDate';
                        break;
                }
                if (in_array($search['plan_date'], [4, 5])) {
                    if ($startTime){
                        $outBookCondition .= " AND ".$dateStr1." >= '{$startTime}'";
                    }
                    if ($endTime){
                        $outBookCondition .= " AND ".$dateStr2." <= '{$endTime}"." 23:59:59"."'";
                    }
                } else {
                    if ($startTime){
                        $outBookCondition .= " AND ".$dateStr." >= '{$startTime}'";
                    }
                    if ($endTime){
                        $outBookCondition .= " AND ".$dateStr." <= '{$endTime}"." 23:59:59"."'";
                    }
                }
                $outBookCondition .= " GROUP BY iBookId ) ";
            }
        } else {
            //选择了时间类型
            if (isset($search['plan_date']) && $search['plan_date'] !== '') {
                $startTime = isset($search['startTime']) && $search['startTime'] ? $search['startTime'] : '';
                $endTime = isset($search['endTime']) && $search['endTime'] ? $search['endTime'] : '';
                switch ($search['plan_date']) {
                    case 0:
                        $dateStr = 'sStartDate';
                        break;
                    case 1:
                        $dateStr = 'sEndDate';
                        break;
                    case 2:
                        $dateStr = 'sRealStartDate';
                        break;
                    case 3:
                        $dateStr = 'sRealEndDate';
                        break;
                    case 4:
                        $dateStr1 = 'sStartDate';
                        $dateStr2 = 'sEndDate';
                        break;
                    case 5:
                        $dateStr1 = 'sRealStartDate';
                        $dateStr2 = 'sRealEndDate';
                        break;
                }
                if (in_array($search['plan_date'], [4, 5])) {
                    if ($startTime){
                        $condition .= " AND A.".$dateStr1." >= '{$startTime}'";
                    }
                    if ($endTime){
                        $condition .= " AND A.".$dateStr2." <= '{$endTime}"." 23:59:59"."'";
                    }
                } else {
                    if ($startTime){
                        $condition .= " AND A.".$dateStr." >= '{$startTime}'";
                    }
                    if ($endTime){
                        $condition .= " AND A.".$dateStr." <= '{$endTime}"." 23:59:59"."'";
                    }
                }
            }
        }
        $sql = [
            'columns' => '*',
            'query' => "SELECT :columns: FROM ( 
            SELECT A.iId, A.iBookId, A.sBookName, A.iDemandStatus, B.iStatus as iBookStatus, A.sProgress, A.sDemand, A.sEndDate, A.sRealStartDate, A.sRealEndDate, A.sStartDate, B.iBookSubject, B.iBookClass  
            FROM `XHRes_ReferencePlan` A LEFT JOIN `XHRes_ReferenceNote` B ON A.iBookId = B.iBookId 
            WHERE {$condition} 
            ORDER BY A.tCreateDate DESC ) C 
            {$outBookCondition}
            GROUP BY iBookId "
        ];
        $enum = $this->registerEnum['referenceApply'];
        $enum['iBookSubject'] = $this->getBookSubjectEnum('subject');
        $enum['iBookClass'] = [0 => ''] + $this->getBookSubjectEnum('grade');
        $data = Main::runSqlPage($sql, $enum);
//        改成异步加载
//        if ($data['rows']) {
//            foreach ($data['rows'] as &$row) {
//                $catalogArr = [];
//                $params = [
//                    'textBookVersion' => 1,
//                    'gradeId' => 1,
//                    'subjectId' => 1
//                ];//这三个参数传任意非空数据即可
//                $books = new Books();
//                $bookInfo = $books->getCatalogsByBookId($row['iBookId'], $params);
//                if (!$bookInfo) {
//                    continue;
//                }
////                $row['sBookName'] = $bookInfo['bookName'];
//                if (isset($bookInfo['catalogs']) && $bookInfo['catalogs']) {
//                    foreach ($bookInfo['catalogs'] as $value) {
//                        $catalogArr[$value['catalogId']] = $value['catalogName'];//列表中展示的章节
//                    }
//                }
//                if ($row['sDemand']) {
//                    $demandArr = [];
//                    $handDemand = explode(',', $row['sDemand']);
//                    foreach ($handDemand as $item) {
//                        if (isset($catalogArr[$item]) && $catalogArr[$item]) {
//                            $demandArr[] = $catalogArr[$item];
//                        }
//                    }
//                    if ($demandArr) {
//                        $row['sDemand'] = implode('，', $demandArr);
//                    }
//                    $rootParentId = $this->handleCateLogName($bookInfo['catalogs'], $handDemand[0], 2);
//                    if (!in_array($rootParentId, $handDemand)) {//加上最高层章节信息
//                        $row['sDemand'] = isset($catalogArr[$rootParentId]) && $catalogArr[$rootParentId] ?
//                            $catalogArr[$rootParentId]. '：' . $row['sDemand'] : $row['sDemand'];
//                    }
//                }
//            }
//        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 返回外部申请的数组书id,[注：在‘教辅申请’页面中增加的排期都为‘外部’,包括‘排期申请’和‘排期计划’按钮中添加，即addType=1、2]
     *
     * @return array
     *
     * create by qgz 20181127
     */
    public function getOutIdArr()
    {
        $allData = XhresReferencePlan::find([
            'columns' => 'iBookId',
            'conditions' => 'bDelete = 0 and (iAddType = 1 or iAddType = 2) and iStatus != 4 ',
        ])->toArray();
        return array_values(array_unique(array_filter(array_column($allData, 'iBookId'))));
    }

    /**
     * 异步加载章节数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190219
     */
    public function getCatalogDataAction()
    {
        $return = $fina = $exist = [];
        $idArr = $this->request->getPost('idArr');
        if (!$idArr) {
            return $this->sendJsonResponse($return);
        }
        $findData = XhresReferencePlan::find([
            'columns' => 'iId, iBookId, sDemand',
            'conditions' => 'iId in ({idArr:array})',
            'bind' => ['idArr' => $idArr]
        ])->toArray();
        if (!$findData) {
            return $this->sendJsonResponse($return);
        }
        $findData = array_column($findData, null, 'iId');
        foreach ($findData as $id => $row) {
            $catalogArr = [];
            $params = [
                'textBookVersion' => 1,
                'gradeId' => 1,
                'subjectId' => 1
            ];//这三个参数传任意非空数据即可
            $books = new Books();
            $bookInfo = $books->getCatalogsByBookId($row['iBookId'], $params);
            if (!$bookInfo) {
                continue;
            }
            if (isset($bookInfo['catalogs']) && $bookInfo['catalogs']) {
                foreach ($bookInfo['catalogs'] as $value) {
                    $catalogArr[$value['catalogId']] = $value['catalogName'];//列表中展示的章节
                }
            }
            if ($row['sDemand']) {
                $demandArr = [];
                $handDemand = explode(',', $row['sDemand']);
                foreach ($handDemand as $item) {
                    $catalogId = ['catalogId' => $item];
                    $books = new Books();
                    $catalogInfo = $books->getCatalogsByCatalogId($catalogId);//根据章节id获取章节数据
                    if ($catalogInfo) {
                        $catalogInfo = array_column($catalogInfo, 'catalogName', 'catalogId');
                        if (isset($catalogInfo[$item]) && $catalogInfo[$item]) {
                            $demandArr[] = $catalogInfo[$item];
                        }
                    }
//                    if (isset($catalogArr[$item]) && $catalogArr[$item]) {
//                        $demandArr[] = $catalogArr[$item];
//                    }
                }
                if ($demandArr) {
                    $exist[$id] = implode('，', $demandArr);
                }
                $rootParentId = $this->handleCateLogName($bookInfo['catalogs'], $handDemand[0], 2);
                if (!in_array($rootParentId, $handDemand)) {//加上最高层章节信息
                    $exist[$id] = isset($catalogArr[$rootParentId]) && $catalogArr[$rootParentId] ?
                        $catalogArr[$rootParentId]. '：' . $exist[$id] : $exist[$id];
                }
            }
        }
        foreach ($idArr as $key => $item) {
            $fina[$key] = isset($exist[$item]) ? $exist[$item] : '';
        }
        return $this->sendJsonResponse($fina);
    }

    /**
     * 更新bookID脚本，跑一次
     *
     *
     * create by qgz 20181218
     */
    public function runBookIdAction()
    {
        $allData = XhresReferencePlan::find(['conditions' => "bDelete = 0 and iAddType = 5 and iBookId is not null and iBookId != '' "]);
        if (!$allData) {
            echo '没有需要更新的数据';
        }
        foreach ($allData as $value) {
            if (!$value->iApplyId) {
                continue;
            }
            $findData = XhresReferenceSchedule::findFirst([
                'conditions' => "bDelete = 0 and iId = :iId: ",
                'bind' => ['iId' => $value->iApplyId]
            ]);
            if ($findData && !$findData->iBookId) {
                $findData->iBookId = $value->iBookId;
                if (!$findData->save()) {
                    echo '更新出错一条数据：iId：' . $findData->iId . '书本ID：' . $value->iBookId .'<br>';
                }
                echo '更成功：iId：' . $findData->iId . '书本ID：' . $value->iBookId .'<br>';
            }
        }
        echo '更新完成';
    }
    
    /**
     * 添加排期计划
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181013
     */
    public function addSchedulePlanAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['bookId']) {
            return $this->sendErrorResponse(400, '缺少书id参数');
        }
        if (!$postData['demand'] || !$postData['beginDate'] || !$postData['endDate']) {
            return $this->sendErrorResponse(400, '请填写完整信息');
        }
        if ($postData['beginDate'] > $postData['endDate']) {
            return $this->sendErrorResponse(400, '开始时间不能大于结束时间');
        }
        $pro = new XhresReferencePlan();
        $pro->iBookId = $postData['bookId'];
        $pro->sProgress = $postData['progress'];
        $pro->sDemand = $postData['demand'] ? implode(',', $postData['demand']) : '';
        $pro->sRealStartDate = $postData['beginDate'];
        $pro->sRealEndDate = $postData['endDate'];
        $pro->sNoteDate = date('Y-m-d H:i:s');
        $pro->iAddType = 3;
        if (!$pro->save()) {
            return $this->sendErrorResponse(500, '保存计划错误');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 根据书id获取章节树数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181015
     */
    public function getCateLogsByBookIdAction()
    {
        $bookId = $this->request->getPost('bookId');
        $showCatalogArr = [];
        $params = [
            'textBookVersion' => 1,
            'gradeId' => 1,
            'subjectId' => 1
        ];//这三个参数传任意非空数据即可
        $books = new Books();
        $result = $books->getCatalogsByBookId($bookId, $params);//获取书章节数据
        if (isset($result['catalogs']) && $result['catalogs']) {
            foreach ($result['catalogs'] as $value) {
                $name = $this->handleCateLogName($result['catalogs'], $value['catalogId']);
                $showCatalogArr[$value['catalogId']] = $name;//下拉选择时展示的章节
            }
        }
        return $this->sendJsonResponse($showCatalogArr);
    }

    /**
     * 设置需求录入状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181016
     */
    public function setDemandStatusAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['bookId'] || !$postData['id']) {
            return $this->sendErrorResponse(400, '没有书id或者排期id，不可操作');
        }
        $pro = XhresReferencePlan::findFirst([
            'conditions' => 'bDelete = 0 and iId = :iId: ',
            'bind' => ['iId' => $postData['id']]
        ]);
        if (!$pro) {
            return $this->sendErrorResponse(500, '没有改需求数据');
        }
        $pro->iDemandStatus = $postData['status'];//是否完成状态
        $pro->sFinishDate = $postData['finishDate'];
//        $pro = XhresReferenceNote::findFirst([
//            'conditions' => 'bDelete = 0 and iDateType = 1 and iBookId = :iBookId: ',
//            'bind' => ['iBookId' => $postData['bookId']]
//        ]);
//        if (!$pro) {
//            $pro = new XhresReferenceNote();
//            $pro->iBookId = $postData['bookId'];
//            $pro->iDateType = 1;
//        }
//        $pro->iStatus = $postData['status'];
//        $pro->sDemandFinishDate = $postData['finishDate'];
//        $pro->sDemandCheckUser = User::getId();
//        $pro->sDemandCheckDate = date('Y-m-d H:i:s', time());
        if (!$pro->save()) {
            return $this->sendErrorResponse(500, '保存出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 设置书本录入状态，iDateType 1为需求录入(已废弃)2为书本录入
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181016
     */
    public function setBookStatusAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['bookId']) {
            return $this->sendErrorResponse(400, '没有书id，不可操作');
        }
        $pro = XhresReferenceNote::findFirst([
            'conditions' => 'bDelete = 0 and iDateType = 2 and iBookId = :iBookId: ',
            'bind' => ['iBookId' => $postData['bookId']]
        ]);
        if (!$pro) {
            $pro = new XhresReferenceNote();
            $pro->iBookId = $postData['bookId'];
            $pro->iDateType = 2;//1为需求录入(已废弃)2为书本录入
        }
        $pro->iStatus = $postData['status'];
        switch ($postData['status']) {
            case 1:
                $pro->sBookProgressDate = $postData['setDate'];
                break;
            case 2:
                $pro->sBookSuspendDate = $postData['setDate'];
                break;
            case 3:
                $pro->sBookFinishDate = $postData['setDate'];
                break;
            default:
                break;
        }
        $pro->sBookCheckDate = User::getId();
        $pro->sBookCheckUser = date('Y-m-d H:i:s', time());
        if (!$pro->save()) {
            return $this->sendErrorResponse(500, '保存出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 刷新书本状态，录入和完成状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181122
     */
    public function refreshPlanBookStatusAction()
    {
        $data = XhresReferencePlan::find([
            'columns' => ' distinct iBookId ',
            'conditions' => ' bDelete = 0 '
        ])->toArray();
        if ($data) {
            $allBookId = array_column($data, 'iBookId');
            $bookNote = XhresReferenceNote::find([
                'columns' => ' distinct iBookId ',
                'conditions' => ' bDelete = 0 '
            ])->toArray();

            $existBookId = array_column($bookNote, 'iBookId');
            $outBookId = array_diff($allBookId, $existBookId);
            if ($existBookId) {//note表中已存在更新状态
                $findData = XhresReferenceNote::find([
                    'conditions' => ' bDelete = 0 and iBookId in ({idArr:array})',
                    'bind' => ['idArr' => $existBookId]
                ]);
                if ($findData) {
                    foreach ($findData as $value) {
                        if ($value->iBookId) {
                            $books = new Books();//先按单个的来
                            $result = $books->getBookDetail($value->iBookId);
                            if ($result && $result['bookId'] == $value->iBookId) {
                                $value->iStatus = $result['bookComplete'] == 1 ? 3 : 4;
                                $value->iBookSubject = $result['subjectId'];
                                $value->iBookClass = $result['gradeId'];
                                if (!$value->save(null, null, true)) {
                                    return $this->sendErrorResponse(
                                        500,
                                        '更新书出错,书id:' . $value->iBookId .',编号id:' . $value->iId
                                    );
                                }
                            }
                        }
                    }
                }
            }
            if ($outBookId) {//Note表中没有插入
                foreach ($outBookId as $insertBookId) {
                    $pro = new XhresReferenceNote();
                    $pro->iBookId = $insertBookId;
                    $pro->iDateType = 2;//书本状态

                    if ($insertBookId) {
                        $books = new Books();//先按单个的来
                        $result = $books->getBookDetail($insertBookId);
                        if ($result && $result['bookId'] == $insertBookId) {
                            $pro->iBookSubject = $result['subjectId'];
                            $pro->iBookClass = $result['gradeId'];
                            $pro->iStatus = $result['bookComplete'] == 1 ? 3 : 4;
                            if (!$pro->save(null, null, true)) {
                                return $this->sendErrorResponse(
                                    500,
                                    '更新书出错,书id:' . $value->iBookId .',编号id:' . $value->iId
                                );
                            }
                        }
                    }
                }
            }

            $data = XhresReferencePlan::find([
                'conditions' => ' bDelete = 0 '
            ]);
            //脚本跑名字：开始
            if ($data) {
                foreach ($data as $v) {
                    if (!$v->iBookId) {
                        continue;
                    }
                    $books = new Books();//先按单个的来
                    $result = $books->getBookDetail($v->iBookId);
                    if ($result && $result['bookId'] == $v->iBookId) {
                        $v->sBookName = $result['bookName'];
                        if (!$v->save(null, null, true)) {
                            return $this->sendErrorResponse(
                                500,
                                '更新书名出错,书id:' . $v->iBookId .',编号id:' . $v->iId
                            );
                        }
                    }
                }
            }
            return $this->sendSuccessResponse('成功');
        } else {
            return $this->sendSuccessResponse('成功，没有需要刷新的数据');
        }
    }

    /**
     * 手机端短信展示计划列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181017
     */
    public function getPlanDetailAction()
    {
        $bookId = $this->request->getQuery('bookId');
        if (!$bookId) {
            return $this->sendViewError('缺少书本id信息');
        }
        $bookId = base64_decode($bookId);
        $this->view->pick('res/referPlanPhone');
        Assets::datetimePicker();
        Assets::select2();
        Assets::sweetAlert2();
        Assets::easyUI('../assets/xh/xhTop.js');
        Assets::easyUI('js/res/referPlanPhone.js');
        $data = XhresReferencePlan::find([
            'conditions' => 'bDelete = 0 and iBookId = :iBookId:',
            'bind' => ['iBookId' => $bookId],
            'order' => 'sRealEndDate DESC, sRealStartDate DESC, sStartDate DESC, sEndDate DESC'
        ])->toArray();
        if (!$data) {
            return $this->sendViewError('暂无该书排期计划信息');
        }
        $bookName = '';
        $catalogArr = [];
        $params = [
            'textBookVersion' => 1,
            'gradeId' => 1,
            'subjectId' => 1
        ];//这三个参数传任意非空数据即可
        $books = new Books();
        $result = $books->getCatalogsByBookId($bookId, $params);//获取书章节数据
        if (isset($result['catalogs']) && $result['catalogs']) {
            foreach ($result['catalogs'] as $value) {
                $catalogArr[$value['catalogId']] = $value['catalogName'];//列表中展示的章节
            }
        }
        if ($data) {
            $applyIds = array_filter(array_unique(array_column($data, 'iApplyId')));
            $applyIds = implode(',', $applyIds);
            $sql = "SELECT A.iId AS applyId, B.sSchoolName AS schoolName 
FROM XHRes_ReferenceApply A LEFT JOIN XHSchool_Info B ON A.iSchoolId = B.iSchoolId 
WHERE A.iId IN ($applyIds);";
            $schoolNameArr = $this->db->fetchAll($sql);
            if ($schoolNameArr) {
                $schoolNameArr = array_column($schoolNameArr, 'schoolName', 'applyId');
            }
            $demandFinishDate = '';
            $demandStatusDate = XhresReferenceNote::findFirst([
                'columns' => 'sDemandFinishDate',
                'conditions' => 'bDelete = 0 and iDateType = 1 and iStatus = 1 and iBookId = :iBookId:',
                'bind' => ['iBookId' => $bookId]
            ]);
            if ($demandStatusDate) {
                $demandFinishDate = $demandStatusDate->sDemandFinishDate;
            }
            foreach ($data as &$value) {
                $bookName = $value['sBookName'];
                switch ($value['iStatus']) {
                    case 0 :
                        $value['iStatusStr'] = '未操作';
                        break;
                    case  1:
                        $value['iStatusStr'] = '<i style="color: green;font-style:normal">同意（默认）</i>';
                        break;
                    case  2:
                        $checkUser = XhsysUser::getUserNameById([$value['sCheckUser']]);
                        $value['iStatusStr'] = '<i style="color: green;font-style:normal">同意（' . $checkUser[$value['sCheckUser']] . '）</i>';
                        break;
                    case  3:
                        $checkUser = XhsysUser::getUserNameById([$value['sCheckUser']]);
                        $msg = '<i style="cursor:pointer;color: red" title="查看原因" class="reason fa fa-question-circle-o" reasonMsg="'.$value['sRefuseReason'].'" '.'></i>';
                        $value['iStatusStr'] = '<i style="color: blue;font-style:normal">不同意（' . $checkUser[$value['sCheckUser']] . '）</i>' . $msg;
                        break;
                    case 4:
                        $checkUser = XhsysUser::getUserNameById([$value['sCheckUser']]);
                        $msg = '<i style="cursor:pointer;color: red" title="查看原因" class="cancel fa fa-question-circle-o" cancelMsg="'.$value['sRefuseReason'].'" '.'></i>';
                        $value['iStatusStr'] = '<i style="color: red;font-style:normal">已取消（' . $checkUser[$value['sCheckUser']] . date('Y-m-d', strtotime($value['sCheckDate'])) . '）</i>' . $msg;
                        break;
                }
                if ($value['sDemand']) {
                    $demandArr = [];
                    $handDemand = explode(',', $value['sDemand']);
                    foreach ($handDemand as $item) {
                        $catalogId = ['catalogId' => $item];
                        $books = new Books();
                        $catalogInfo = $books->getCatalogsByCatalogId($catalogId);//根据章节id获取章节数据
                        if ($catalogInfo) {
                            $catalogInfo = array_column($catalogInfo, 'catalogName', 'catalogId');
                            if (isset($catalogInfo[$item]) && $catalogInfo[$item]) {
                                $demandArr[] = $catalogInfo[$item];
                            }
                        }
//                        if (isset($catalogArr[$item]) && $catalogArr[$item]) {
//                            $demandArr[] = $catalogArr[$item];
//                        }
                    }
                    if ($demandArr) {
                        $value['sDemand'] = implode('，', $demandArr);
                    }
                    $rootParentId = $this->handleCateLogName($result['catalogs'], $handDemand[0], 2);
                    if (!in_array($rootParentId, $handDemand)) {//加上最高层章节信息
                        $value['sDemand'] = isset($catalogArr[$rootParentId]) && $catalogArr[$rootParentId] ?
                            $catalogArr[$rootParentId] . '：' . $value['sDemand'] : $value['sDemand'];
                    }
                }
                $value['sDemand'] .= isset($schoolNameArr[$value['iApplyId']]) && $schoolNameArr[$value['iApplyId']] ? '&nbsp&nbsp【' . $schoolNameArr[$value['iApplyId']] . '】' : '';
                if ($demandFinishDate && $value['sRealEndDate']) {
                    if ($value['sRealEndDate'] < $demandFinishDate) {
                        $color = 'red';
                    } else if ($value['sRealEndDate'] == $demandFinishDate) {
                        $color = 'blue';
                    } else if ($value['sRealEndDate'] > $demandFinishDate) {
                        $color = 'green';
                    } else {
                        $color = 'black';
                    }
                    $value['sDemand'] = '<i style="color: ' . $color . ';font-style:normal">' . $value['sDemand'] . '</i>';
                }
                $value['isCreateMan'] = ($value['iCreateUserId'] == User::getId()) ? 1 : 2 ;//是否是申请人，结合操作按钮权限
            }
        }
        $power = ['add' => false, 'del' => false, 'check' => false];
        if (Power::exist('Res_SchedulePlan_Add')) {
            $power['add'] = true;
        }
        if (Power::exist('Res_SchedulePlan_Del')) {
            $power['del'] = true;
        }
        if (Power::exist('Res_SchedulePlan_Check')) {
            $power['check'] = true;
        }
        return $this->view->setVars([
            'bookName' => $bookName,
            'data' => $data,
            'power' => $power,
        ]);
    }

    /**
     * 排期查询
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181026
     */
    public function planSummaryAction()
    {
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('res/scheduleSummary');
        Main::showNavPosition();
        Assets::easyUI('js/res/scheduleSummary.js');
//        if (!Power::exist('Res_SchedulePlan_Summary')) {
//            return $this->sendViewError('对不起，您没有查看此页面的权限');
//        }
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'search_date', 'style' => 'width: 100px;'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'plan_startTime'];
        $listSearchArr[] = ['label' => ' ~ ', 'type' => 'text', 'id' => 'plan_endTime'];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'plan_status',
            'data' => ['' => '--计划状态--'] + [0 => '未操作', 1 => '同意', 3 => '不同意', 4 => '取消', ], 'style' => 'width: 100px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'deal_status',
            'data' => ['' => '--处理状态--'] + $this->dealStatus, 'style' => 'width: 100px;'
        ];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        $listButtonArr[] = ['id' => 'bt_list_handleStatus', 'text' => '处理', 'plain' => 'true', 'icon' => 'fa-commenting-o'];
        $power['add'] = false;
        if (Power::exist('Res_SchedulePlan_Add')) {
            $power['add'] = true;
        }
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHRes_ScheduleSummary', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'power' => $power,
        ]);
    }

    /**
     * 获取排期查询数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181026
     */
    public function getScheduleSummaryDataAction()
    {
        $search = $this->request->getPost('search');
        $parameters = [
            'conditions' => ' bDelete = 0 ',
            'order' => 'tCreateDate DESC'
        ];
        if (isset($search['plan_status']) && $search['plan_status'] !== ''){
            if ($search['plan_status'] == 1) {
                $parameters['conditions'] .= " AND (iStatus = 1 OR iStatus = 2) ";
            } else {
                $parameters['conditions'] .= " AND iStatus = " . $search['plan_status'];
            }
        }
        if (isset($search['deal_status']) && $search['deal_status'] !== '') {
            $parameters['conditions'] .= " AND iDealStatus = " . $search['deal_status'];
        }

        $startTime = isset($search['startTime']) && $search['startTime'] ? $search['startTime'] : '';
        $endTime = isset($search['endTime']) && $search['endTime'] ? $search['endTime'] : '';
        switch ($search['plan_date']) {
            case 0:
                $dateStr = 'sStartDate';
                break;
            case 1:
                $dateStr = 'sEndDate';
                break;
            case 2:
                $dateStr = 'sRealStartDate';
                break;
            case 3:
                $dateStr = 'sRealEndDate';
                break;
            case 4:
                $dateStr1 = 'sStartDate';
                $dateStr2 = 'sEndDate';
                break;
            case 5:
                $dateStr1 = 'sRealStartDate';
                $dateStr2 = 'sRealEndDate';
                break;
        }
        if (in_array($search['plan_date'], [4, 5])) {
            if ($startTime){
                $parameters['conditions'] .= " AND ".$dateStr1." >= '{$startTime}'";
            }
            if ($endTime){
                $parameters['conditions'] .= " AND ".$dateStr2." <= '{$endTime}"." 23:59:59"."'";
            }
        } else {
            if ($startTime){
                $parameters['conditions'] .= " AND ".$dateStr." >= '{$startTime}'";
            }
            if ($endTime){
                $parameters['conditions'] .= " AND ".$dateStr." <= '{$endTime}"." 23:59:59"."'";
            }
        }

        Main::runSearchVagueConditions($parameters['conditions'], ['sBookName', 'iBookId', 'sProgress', 'sRefuseReason']);
        $enum['iDemandStatus'] = $this->registerEnum['referenceApply']['iDemandStatus'];
        $enum['iStatus'] = $this->scheduleSummary;
        $enum['iDealStatus'] = $this->dealStatus;
        $data = Main::runModelPage('Admin\Models\res\XhresReferencePlan', $parameters, $enum);
        Main::runUserName($data['rows'],['sCheckUser' => 'sCheckUser']);
        if ($data['rows']) {
            foreach ($data['rows'] as &$row) {
                $row['statusName'] = $row['iStatus'];
                $row['dealStatusName'] = $row['iDealStatus'];
//                改成异步加载
//                $catalogArr = [];
//                $params = [
//                    'textBookVersion' => 1,
//                    'gradeId' => 1,
//                    'subjectId' => 1
//                ];//这三个参数传任意非空数据即可
//                $books = new Books();
//                $bookInfo = $books->getCatalogsByBookId($row['iBookId'], $params);
//                if (!$bookInfo) {
//                    continue;
//                }
//                if (isset($bookInfo['catalogs']) && $bookInfo['catalogs']) {
//                    foreach ($bookInfo['catalogs'] as $value) {
//                        $catalogArr[$value['catalogId']] = $value['catalogName'];//列表中展示的章节
//                    }
//                }
//                if ($row['sDemand']) {
//                    $demandArr = [];
//                    $handDemand = explode(',', $row['sDemand']);
//                    foreach ($handDemand as $item) {
//                        if (isset($catalogArr[$item]) && $catalogArr[$item]) {
//                            $demandArr[] = $catalogArr[$item];
//                        }
//                    }
//                    if ($demandArr) {
//                        $row['sDemand'] = implode('，', $demandArr);
//                    }
//                    $rootParentId = $this->handleCateLogName($bookInfo['catalogs'], $handDemand[0], 2);
//                    if (!in_array($rootParentId, $handDemand)) {//加上最高层章节信息
//                        $row['sDemand'] = isset($catalogArr[$rootParentId]) && $catalogArr[$rootParentId] ?
//                            $catalogArr[$rootParentId] . '：' . $row['sDemand'] : $row['sDemand'];
//                    }
//                }
                if ($row['iStatus'] == '不同意') {
                    $dealColor = $row['iDealStatus'] == '已处理' ? 'green;color:white' : '#87CEFA';
                    $row['iDealStatus'] = '<div style=" background-color: '.$dealColor.'">'.$row['iDealStatus'].'</div>';
                } else {
                    $row['iDealStatus'] = '';
                }
                switch ($row['iStatus']) {
                    case '未操作':
                        $color = '';
                        break;
                    case '不同意':
                        $color = 'red;color:white';
                        break;
                    case '已取消':
                        $color = 'yellow';
                        break;
                    default :
                        $color = 'green;color:white';
                        break;
                }
                $row['iStatus'] = '<div style=" background-color: '.$color.'">'.$row['iStatus'].'</div>';
            }
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 保存处理信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181029
     */
    public function setPlanDealStatusAction()
    {
        $idArr = $this->request->getPost('id');
        $dealMsg = $this->request->getPost('dealMsg');
        if (!$idArr || !$dealMsg) {
            return $this->sendErrorResponse(400, '请选择或填写完整信息');
        }
        $data = XhresReferencePlan::find([
            'conditions' => " bDelete = 0 and iId in ({idArr:array}) ",
            'bind' => ['idArr' => $idArr]
        ]);
        if (!$data) {
            return $this->sendErrorResponse(500, '找不到数据');
        }
        foreach ($data as $datum) {
            $datum->iDealStatus = 1;
            $datum->sDealMsg .= $dealMsg . '【' . Main::getLoginUserInfo('userName') . date('Y-m-d H:i:s') . '】';
            if (!$datum->save()) {
                return $this->sendErrorResponse(400, '保存数据错误，id：' . $datum->iId);
            }
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 教辅排期（内部人员用）页
     *
     * @return \Phalcon\Mvc\View|string
     * @throws \Helpers\XhException
     *
     * create by qgz 20181123
     */
    public function referenceScheduleAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/res/referenceSchedule.js');
        if (!Power::exist('Res_ReferSchedule')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_applySubject','multiple' => true,
            'data' => ['' => '-申请科目-'] + $this->getEnumClass(),'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_applyClass','multiple' => true,
            'data' => ['' => '-申请年级-'] + XhsysEnum::getEnumByNodeName('年级'), 'style' => 'width: 85px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_applyVolume','multiple' => true,
            'data' => ['' => '-上下册-'] + [1 => '上册', 2 => '下册', 3 => '全册'], 'style' => 'width: 75px;'
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_app', 'style' => 'width:100px;',
            'data' => ['' => '-选择应用-'] + App::getAppCodes()];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_plan',
            'data' => ['' => '-排期计划-'] + $this->registerEnum['referenceApply']['iExistPlan']
        ];
        $listSearchArr[] = [
            'label' => '    ','type' => 'select', 'id' => 'list_search_existId',
            'data' => ['' => '-存在id-'] + $this->registerEnum['referenceApply']['bExistBookId']
        ];
        $listSearchArr[] = [
            'label' => ' 搜索：','type' => 'select', 'id' => 'list_search_type', 'data' => ['1' => '编号', '2' => '其他'],
            'style' => 'width: 60px;'
        ];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        $listSearchArr[] = ['type'=>'button', 'id'=>'bt_list_search', 'text' => '查找', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        if (Power::exist('Res_ReferSchedule_Add')) {
            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'增加申请', 'plain'=>'true', 'icon'=>'fa-plus'];
        }
        if (Power::exist('Res_ReferSchedule_Apply')) {
            $listButtonArr[] = ['id' => 'bt_list_planApply', 'text' => '排期申请', 'plain' => 'true', 'icon' => 'fa-pencil-square-o'];
        }
        if (Power::exist('Res_ReferSchedule_AddSchedule')) {
            $listButtonArr[] = ['id'=>'bt_list_addSchedulePlan', 'text'=>'排期计划', 'plain'=>'true', 'icon'=>'fa-calendar-check-o'];
        }
        $power['modify'] = false;
        if (Power::exist('Res_ReferSchedule_Edit')) {
            $power['modify'] = true;
        }
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHRes_ReferenceSchedule', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'power' => $power
        ]);
    }

    /**
     * 获取教辅排期申请数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181123
     */
    public function getReferenceScheduleAction()
    {
        $search = $this->request->getPost('search');
        $parameters = [
            'columns' => '*',
            'conditions' => ' bDelete = 0 ',
            'order' => 'tCreateDate DESC'
        ];
        if ($search['applySubject'] !== '' && $search['applySubject'] !== null) {
            $applySubjectStatus = $this->handleSearchStatus($search['applySubject']);
            if ($applySubjectStatus) {
                $parameters['conditions'] .= " AND iSubject in ($applySubjectStatus)";
            }
        }
        if ($search['applyClass'] !== '' && $search['applyClass'] !== null) {
            $applyClassStatus = $this->handleSearchStatus($search['applyClass']);
            if ($applyClassStatus) {
                $parameters['conditions'] .= " AND iClassId in ($applyClassStatus)";
            }
        }
        if ($search['applyVolume'] !== '' && $search['applyVolume'] !== null) {
            $applyVolumeStatus = $this->handleSearchStatus($search['applyVolume']);
            if ($applyVolumeStatus) {
                $parameters['conditions'] .= " AND iVolumeId in ($applyVolumeStatus)";
            }
        }
        if ($search['app'] !== '' && $search['app'] !== null) {
            $parameters['conditions'] .= " AND sAppCode = '{$search['app']}'";
        }
        if ($search['existId'] !== '' && $search['existId'] !== null && in_array($search['existId'], [0, 1])) {
            if ($search['existId'] == 0) {
                $parameters['conditions'] .= " AND (iBookId is null OR iBookId = '') ";
            } else {
                $parameters['conditions'] .= " AND iBookId is not null AND iBookId != '' ";
            }
        }
        if ($search['plan'] !== '' && $search['plan'] !== null) {//查询是否有排期类型
            $bookIdArr = $this->getBookIdArr($search['plan']);
            if ($search['plan'] == 0 && $bookIdArr) {
                $parameters['conditions'] .= " AND iBookId NOT IN ({iBookId:array})";
                $parameters['bind'] = ['iBookId' => $bookIdArr];
            } elseif ($search['plan'] != 0) {
                if (!$bookIdArr) {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                } else {
                    $parameters['conditions'] .= " AND iBookId IN ({iBookId:array})";
                    $parameters['bind'] = ['iBookId' => $bookIdArr];
                }
            }
        }

        $searchLineArr = [];
        if ($search['vague'] && $search['searchType'] == 2) {//普通搜索
            $searchLineArr = ['sBookName', 'sTypeIn'];
        }
        if ($search['vague'] && $search['searchType'] == 1) {//编号搜索
            if ($search['vague']) {
                if (is_numeric($search['vague'])) {
                    $parameters['conditions'] .= " and iId = '{$search['vague']}'";
                } else {
                    return $this->sendDataGridError('搜索编号请输入纯数字编号');
                }
            }
        }
        try {
            Main::runSearchVagueConditions($parameters['conditions'], $searchLineArr);
            $enum = $this->registerEnum['referenceApply'];
            $enum['iClassId'] = XhsysEnum::getEnumByNodeName('年级');
            $enum['iSubject'] = XhsysEnum::getEnumByNodeName('学科');
            $enum['sAppCode'] = App::getAppCodes();
            $data = Main::runModelPage('Admin\Models\res\XhresReferenceSchedule', $parameters, $enum);
            Main::runUserName($data['rows'],['iCreateUserId' => 'sCreateUserName', 'iLastModifyUserId' => 'iLastModifyUserName']);
            $this->addInfo($data['rows']);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 添加其他信息
     *
     * @param $data
     *
     * @return bool
     *
     * create by qgz 20181126
     */
    public function addInfo(&$data)
    {
        foreach ($data as &$value) {
            $value['bookName'] = $value['sBookName'];
            $value['iClassId'] .= $value['iVolumeId'] ? ($value['iVolumeId'] == 1 ? '(上)' : ($value['iVolumeId'] == 2 ? '(下)' : '(全)')) : '';
            if ($value['iBookId']) {
                $statusArr = $this->getPlanExistArrById($value['iBookId']);
                if ($statusArr) {
                    $statusStr = '';
                    if (in_array(2, $statusArr)) {
                        $statusStr .= "<i title='该书有排期新申请' class='fa fa-thumb-tack' style='color:dodgerblue;'></i>  ";
                    }
                    if (in_array(3, $statusArr)) {
                        $statusStr .= "<i title='该书有排期已过期' class='fa fa-history' style='color:black;'></i>  ";
                    }
                    if (in_array(1, $statusArr)) {
                        $statusStr .= "<i title='该书本已有排期计划' class='fa fa-flag' style='color:red;'></i>  ";
                    }
                    $value['bookName'] = $statusStr . $value['bookName'];
                }
            }
        }
        return true;
    }

    /**
     * 创建教辅申请页(内部)
     *
     * @return \Phalcon\Mvc\View
     *
     * create by qgz 20181126
     */
    public function addReferenceScheduleAction()
    {
        if (!Power::exist('Res_ReferSchedule_Add')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        Assets::select2();
        Assets::easyUI('js/res/addReferenceSchedule.js');
        $this->view->pick('res/addReferenceSchedule');
        return $this->view->setVars(['modify' => 1]);//1创建2修改
    }

    /**
     * 修改教辅申请页(内部)
     *
     * @return \Phalcon\Mvc\View
     *
     * create by qgz 20181126
     */
    public function modifyReferScheduleAction()
    {
        if (!Power::exist('Res_ReferSchedule')) {
            return $this->sendViewError('您没有查看此页面的权限');
        }
//        if (!Power::exist('Res_ReferSchedule_Edit') && !Power::exist('Res_ReferSchedule_View')) {//该权限废弃
//            return $this->sendViewError('对不起，您没有查看此页面的权限');
//        } else {
//            if (!Power::exist('Res_ReferSchedule_View')) {
//                return $this->sendViewError('对不起，您没有查看此页面的权限');
//            }
//        }
        $id = $this->request->getQuery('id');
        if (!$id) {
            return $this->sendViewError('缺少参数id');
        }
        $data = XhresReferenceSchedule::findFirst(['conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $id]]);
        if (!$data) {
            return $this->sendViewError('找不到数据');
        }
        $data = $data->toArray();
        Assets::select2();
        Assets::easyUI('js/res/addReferenceSchedule.js');
        $this->view->pick('res/addReferenceSchedule');
        return $this->view->setVars(['modify' => 2, 'iId' => $id, 'applyDataArr' => $data]);//1创建2修改
    }

    /**
     * 保存教辅排期（内部）数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181126
     */
    public function saveReferenceScheduleAction()
    {
        $data = $this->request->getPost();
        if (!$data['grade'] || !$data['subject'] || !$data['bookName'] || !$data['typeIn'] || !$data['app']) {
            return $this->sendErrorResponse(400, '请填写完整信息');
        }
        $referenceSchedule = new XhresReferenceSchedule();
        $referenceSchedule->iClassId = trim($data['grade']);
        $referenceSchedule->iSubject = trim($data['subject']);
        $referenceSchedule->sBookName = trim($data['bookName']);
        $referenceSchedule->sTypeIn = trim($data['typeIn']);
        $referenceSchedule->iVolumeId = trim($data['volume']);
        $referenceSchedule->sAppCode = trim($data['app']);
        $referenceSchedule->sBuyUrl = trim($data['buyUrl']);
        $referenceSchedule->sRemark = $data['remark'];
        if (!$referenceSchedule->save()) {
            return $this->sendErrorResponse(500, '保存失败', $referenceSchedule->getError());
        } else {
            return $this->sendSuccessResponse('成功');
        }
    }

    /**
     * 保存修改教辅排期（内部）数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181126
     */
    public function saveModifyReferScheduleAction()
    {
        $data = $this->request->getPost();
        if (!$data['iId']) {
            return $this->sendErrorResponse(400, '缺少数据id');
        }
        if (!$data['grade'] || !$data['subject'] || !$data['bookName'] || !$data['typeIn'] || !$data['app']) {
            return $this->sendErrorResponse(400, '请填写完整信息');
        }
        $referenceSchedule = XhresReferenceSchedule::findFirst([
            'conditions' => 'bDelete = 0 and iId = :iId:',
            'bind' => ['iId' => $data['iId']]
        ]);
        if (!$referenceSchedule) {
            return $this->sendErrorResponse(400, '找不到数据');
        }
        $referenceSchedule->iClassId = trim($data['grade']);
        $referenceSchedule->iSubject = trim($data['subject']);
        $referenceSchedule->sBookName = trim($data['bookName']);
        $referenceSchedule->sTypeIn = trim($data['typeIn']);
        $referenceSchedule->sAppCode = trim($data['app']);
        $referenceSchedule->iVolumeId = trim($data['volume']);
        $referenceSchedule->sBuyUrl = trim($data['buyUrl']);
        $referenceSchedule->sRemark = $data['remark'];
        if (!$referenceSchedule->save()) {
            return $this->sendErrorResponse(500, '保存失败', $referenceSchedule->getError());
        } else {
            return $this->sendSuccessResponse('成功');
        }
    }

    /**
     * 录入确认页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181126
     */
    public function checkTypeInAction()
    {
        if (!Power::exist('Res_ReferenceApply_CheckTypeIn')) {
            return $this->sendViewError('你没有权限查看此页面');
        }
        $id = $this->request->getQuery('id');
        if (!$id) {
            return $this->sendViewError('缺少数据id');
        }
        Assets::select2();
        Assets::easyUI('js/res/checkTypeIn.js');
        $this->view->pick('res/checkTypeIn');
        $existCheck = false;
        $checkHistory = [];
        $existData = XhresReferenceCheck::find([
            'columns' => '*',
            'conditions' => 'bDelete = 0 and iApplyId = :iApplyId: and iStatus != 0 ',
            'bind' => ['iApplyId' => $id]
        ])->toArray();
        if ($existData) {
            $existCheck = true;
            foreach ($existData as $datum) {
                $staffInfo = Hrm::getStaffInfo([$datum['iCheckId']]);
                $checkHistory[] = [
                    'date' => $datum['tCreateDate'],
                    'type' => $datum['iStatus'] == 1 ? '同意' : ($datum['iStatus'] == 2 ? '不同意' : ''),
                    'user' => isset($staffInfo[$datum['iCheckId']]) && $staffInfo[$datum['iCheckId']] ? $staffInfo[$datum['iCheckId']]['staffName'] : '',
                    'msg' => $datum['sCheckMsg']
                ];
            }
        }
        $teachDataArr = XhhrmStaff::getStaff();//老师列表
        $data = XhresReferenceApply::findFirst([
            'columns' => 'iBookId, sBookName, iClassId, iVolumeId, iSubject',
            'conditions' => 'bDelete = 0 and iId = :id:',
            'bind' => ['id' => $id]
        ]);
        if (!$data) {
            return $this->sendViewError('找不到数据');
        }
        $data = $data->toArray();
        $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
        $subjectEnum = XhsysEnum::getEnumByNodeName('学科');
        $data['iSubject'] = isset($subjectEnum[$data['iSubject']]) ? $subjectEnum[$data['iSubject']] : $data['iSubject'];
        $data['iClassId'] = isset($gradeEnum[$data['iClassId']]) ? $gradeEnum[$data['iClassId']] : $data['iClassId'];
        $data['iClassId'] .= $data['iVolumeId'] ?
            ($data['iVolumeId'] == 1 ? '(上)' : ($data['iVolumeId'] == 2 ? '(下)' : '(全)')) : '';
        return $this->view->setVars([
            'teacher' => $teachDataArr,
            'id' => $id,
            'book' => $data,
            'existCheck' => $existCheck,
            'checkHistory' => $checkHistory
        ]);
    }

    /**
     * 教辅录取确认二维码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181126
     */
    public function getCheckTypeInQRAction()
    {
        $id = $this->request->getPost('id');
        $teachId = $this->request->getPost('teachId');
        if (!$id) {
            return $this->sendSuccessResponse('');
        }
        try {
            return $this->sendSuccessResponse((new QrCode(Tool::buildUrl('res/doCheckTypeIn', ['id' => $id, 'teachId' => $teachId])))->writeDataUri(), false);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 录入确认操作页面(二维码扫出页面)
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181127
     */
    public function doCheckTypeInAction()
    {
        $id = $this->request->getQuery('id');
        $teachId = $this->request->getQuery('teachId');
        if (!$id) {
            return $this->sendViewError('缺少数据id');
        }
        if (!$teachId) {
            return $this->sendViewError('缺少老师id');
        }
        if ($teachId != User::getId()) {
            return $this->sendViewError('您不是该申请指定的确认人员。');
        }
        Assets::sweetAlert2();
        Assets::easyUI('../assets/xh/xhTop.js');
        Assets::easyUI('js/res/doCheckTypeIn.js');
        $this->view->pick('res/doCheckTypeIn');
        $teachName = XhsysUser::findFirst([
            'columns' => 'iUserId, sUserName',
            'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
            'bind' => ['iUserId' => $teachId]
        ]);
        $staffInfo = Hrm::getStaffInfo([$teachId]);
        $data = XhresReferenceApply::findFirst([
            'columns' => 'iBookId, sBookName, iClassId, iVolumeId, iSubject',
            'conditions' => 'bDelete = 0 and iId = :id:',
            'bind' => ['id' => $id]
        ]);
        if (!$data) {
            return $this->sendViewError('找不到数据');
        }
        $data = $data->toArray();
        $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
        $subjectEnum = XhsysEnum::getEnumByNodeName('学科');
        $data['iSubject'] = isset($subjectEnum[$data['iSubject']]) ? $subjectEnum[$data['iSubject']] : $data['iSubject'];
        $data['iClassId'] = isset($gradeEnum[$data['iClassId']]) ? $gradeEnum[$data['iClassId']] : $data['iClassId'];
        $data['iClassId'] .= $data['iVolumeId'] ?
            ($data['iVolumeId'] == 1 ? '(上)' : ($data['iVolumeId'] == 2 ? '(下)' : '(全)')) : '';
        return $this->view->setVars(['teacherName' => $staffInfo[$teachId]['staffName'], 'teachId' => $teachId, 'id' => $id, 'book' => $data]);
    }

    /**
     * 操作同意不同意状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181127
     */
    public function handleCheckTypeInAction()
    {
        $data = $this->request->getPost();
        if (!$data['id'] || !$data['teach'] || !$data['type']) {
            return $this->sendErrorResponse(400, '参数错误');
        }
        if ($data['teach'] != User::getId()) {
            return $this->sendErrorResponse(400, '该申请未指定你确认，你无权操作');
        }
        $obj = new XhresReferenceCheck();
        $obj->iApplyId = $data['id'];
        $obj->iStatus = $data['type'];
        $obj->iCheckId = $data['teach'];
        $obj->sCheckMsg = $data['checkMsg'];
        if (!$obj->save()) {
            return $this->sendErrorResponse(500, '保存数据出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 教辅录取确认页面
     *
     * @return \Phalcon\Mvc\View
     *
     * create by qgz 20181127
     */
    public function checkTypeInListAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        if (!Power::exist('Res_CheckTypeIn')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        Assets::easyUI('js/res/checkTypeInList.js');
        $delayEnum = ['' => '--状态--'] + $this->checkTypeStatus;
        $msgEnum = ['' => '--确认信息--'] + [0 => '无', 1 => '有'];
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'list_status', 'style' => 'width: 70px;', 'data' => $delayEnum];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'list_checkMsg', 'data' => $msgEnum];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        $listSearchArr[] = ['type'=>'button', 'id'=>'bt_list_search', 'text' => '查找', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
//        if (Power::exist('Res_CheckTypeIn_AddRemark')) {
            $listButtonArr[] = ['id'=>'bt_list_addRemark', 'text'=>'添加备注', 'plain'=>'true', 'icon'=>'fa-plus'];
//        }
//        if (Power::exist('Res_CheckTypeIn_AddCheckMsg')) {
            $listButtonArr[] = ['id'=>'bt_list_addCheckMsg', 'text'=>'添加确认信息', 'plain'=>'true', 'icon'=>'fa-pencil'];
//        }
        $listButtonArr[] = ['id'=>'bt_list_checkHistory', 'text'=>'审核历史', 'plain'=>'true', 'icon'=>'fa-history'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHRes_ReferCheckTypeInList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ]);
    }

    /**
     * 获取录取确认列表数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by qgz 20181127
     */
    public function getCheckTypeInListAction()
    {
        $status = $this->request->getPost('status');
        $search = $this->request->getPost('search');
        $checkMsg = $this->request->getPost('checkMsg');
        $condition = ' a.bDelete = 0 and b.bDelete = 0 ';
        if ($status) {
            $condition .= " and a.iStatus = {$status} ";
        }
        if ($checkMsg === 0 or $checkMsg === '0') {
            $condition .= " and (a.sCheckMsg is null or a.sCheckMsg = '') ";
        } elseif ($checkMsg == 1) {
            $condition .= " and a.sCheckMsg is not null and a.sCheckMsg != '' ";
        }
        if ($search['vague']) {
            $userIdArr = Hrm::searchStaffUser($search['vague']);
            if (!empty($userIdArr)){
                $userIdArr = implode("','", $userIdArr);
                $condition .= " AND ( b.sBookName LIKE '%{$search['vague']}%' OR a.iCheckId in ('" . $userIdArr . "'))";
            } else {
                $condition .= " and b.sBookName like '%{$search['vague']}%' ";
            }
        }
        $allDataNum = XhresReferenceCheck::find(['columns' => 'count(*) as num'])->toArray();
        $allDataNum = $allDataNum[0]['num'];
        $sql = [
            'columns' => ' * ',
            'query' => "SELECT :columns: FROM ( SELECT a.*, b.iClassId,b.iVolumeId,b.iSubject,b.iBookId,b.sBookName FROM XHRes_ReferenceCheck a LEFT JOIN XHRes_ReferenceApply b ON a.iApplyId = b.iId WHERE {$condition} ORDER BY a.tCreateDate DESC LIMIT {$allDataNum}) c GROUP BY iApplyId ORDER BY tCreateDate DESC"
        ];
        $data = Main::runSqlPage($sql, ['iStatus' => $this->checkTypeStatus]);
        Hrm::runStaffNameByUserId($data['rows'], ['iCheckId' => 'iCheckId', 'iLastModifyUserId' => 'iLastModifyUserId'], true);
        if ($data['rows']) {
            $this->addOtherCheckMsg($data);
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 添加其他信息
     *
     * @param $data
     *
     * create by qgz 20181221
     */
    public function addOtherCheckMsg(&$data)
    {
        $subject = XhsysEnum::getEnumByNodeName('学科');
        $grade   = XhsysEnum::getEnumByNodeName('年级');
        //展示小旗子
        $params = [
            'conditions' => " bDelete = 0 and (sCheckMsg is null or sCheckMsg = '') and iStatus = 2 ",
            'groupBy' => 'iApplyId'
        ];
        $dataApplyIdArr = array_values(array_filter(array_unique(array_column($data['rows'], 'iApplyId'))));
        if ($dataApplyIdArr) {
            $params['conditions'] .= ' and iApplyId in ({idArr:array}) ';
            $params['bind'] = ['idArr' => $dataApplyIdArr];
        }
        $applyId = XhresReferenceCheck::find($params)->toArray();
        $applyId = array_values(array_filter(array_unique(array_column($applyId, 'iApplyId'))));
        foreach ($data['rows'] as &$datum) {
            $datum['nowUserId'] = User::getId();
            $datum['iSubject'] = isset($subject[$datum['iSubject']]) ? $subject[$datum['iSubject']] : '';
            $datum['iClassId'] = isset($grade[$datum['iClassId']]) ? $grade[$datum['iClassId']] : '';
            $datum['iClassId'] .= $datum['iVolumeId'] ? ($datum['iVolumeId'] == 1 ? '(上)' : ($datum['iVolumeId'] == 2 ? '(下)' : '(全)')) : '';
            if (in_array($datum['iApplyId'], $applyId)) {
                $datum['iStatus'] = "<i title='有不同意状态未填写确认信息；双击可完善该信息' class='fa fa-exclamation-triangle' style='color:red;'></i>  " . $datum['iStatus'];
            }
        }
    }

    /**
     * 保存教辅录入确认备注信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181127
     */
    public function setCheckTypeInRemarkAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['id']) {
            return $this->sendErrorResponse(400, '缺少参数id');
        }
        if (!$postData['remark']) {
            return $this->sendErrorResponse(400, '备注不能为空');
        }
        $existData = XhresReferenceCheck::findFirst([
            'conditions' => 'bDelete = 0 and iId = :iId:',
            'bind' => ['iId' => $postData['id']]
        ]);
        if (!$existData) {
            return $this->sendErrorResponse(400, '找不到数据');
        }
        if ($existData->iCheckId != User::getId()) {
            return $this->sendErrorResponse(400, '仅确认老师可填写备注');
        }
        $existData->sRemark .= $existData->sRemark ? '；' . $postData['remark'] . '[' . date('Y-m-d H:i:s') . ']' : $postData['remark'] . '[' . date('Y-m-d H:i:s') . ']';
        if (!$existData->save()) {
            return $this->sendErrorResponse(400, '保存数据出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 保存教辅录入确认信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181212
     */
    public function setCheckMsgAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['id']) {
            return $this->sendErrorResponse(400, '缺少参数id');
        }
        if (!$postData['checkMsg']) {
            return $this->sendErrorResponse(400, '确认信息不能为空');
        }
        $existData = XhresReferenceCheck::findFirst([
            'conditions' => 'bDelete = 0 and iId = :iId:',
            'bind' => ['iId' => $postData['id']]
        ]);
        if (!$existData) {
            return $this->sendErrorResponse(400, '找不到数据');
        }
        if ($existData->iCheckId != User::getId()) {
            return $this->sendErrorResponse(400, '仅确认老师可填写');
        }
        $existData->sCheckMsg .= $existData->sCheckMsg ? '；' . $postData['checkMsg'] . '[' . date('Y-m-d H:i:s') . ']' : $postData['checkMsg'] . '[' . date('Y-m-d H:i:s') . ']';
        if (!$existData->save()) {
            return $this->sendErrorResponse(400, '保存数据出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 录入确认记录
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181221
     */
    public function checkTypeInHistoryAction()
    {
        $id = $this->request->getQuery('id');
        if (!$id) {
            return $this->sendViewError('缺少数据id');
        }
        Assets::select2();
        Assets::easyUI('js/res/checkTypeInHistory.js');
        $this->view->pick('res/checkTypeInHistory');
        $checkHistory = [];
        $existData = XhresReferenceCheck::find([
            'columns' => '*',
            'conditions' => 'bDelete = 0 and iApplyId = :iApplyId: and iStatus != 0 ',
            'bind' => ['iApplyId' => $id]
        ])->toArray();
        if ($existData) {
            foreach ($existData as $datum) {
                $staffInfo = Hrm::getStaffInfo([$datum['iCheckId']]);
                $checkHistory[] = [
                    'date' => $datum['tCreateDate'],
                    'type' => $datum['iStatus'] == 1 ? '同意' : ($datum['iStatus'] == 2 ? '不同意' : ''),
                    'user' => isset($staffInfo[$datum['iCheckId']]) && $staffInfo[$datum['iCheckId']] ? $staffInfo[$datum['iCheckId']]['staffName'] : '',
                    'msg' => $datum['sCheckMsg'],
                    'id' => $datum['iId'],
                    'checkId' => $datum['iCheckId']
                ];
            }
        }
        $data = XhresReferenceApply::findFirst([
            'columns' => 'iBookId, sBookName, iClassId, iVolumeId, iSubject',
            'conditions' => 'bDelete = 0 and iId = :id:',
            'bind' => ['id' => $id]
        ]);
        if (!$data) {
            return $this->sendViewError('找不到数据');
        }
        $data = $data->toArray();
        $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
        $subjectEnum = XhsysEnum::getEnumByNodeName('学科');
        $data['iSubject'] = isset($subjectEnum[$data['iSubject']]) ? $subjectEnum[$data['iSubject']] : $data['iSubject'];
        $data['iClassId'] = isset($gradeEnum[$data['iClassId']]) ? $gradeEnum[$data['iClassId']] : $data['iClassId'];
        $data['iClassId'] .= $data['iVolumeId'] ?
            ($data['iVolumeId'] == 1 ? '(上)' : ($data['iVolumeId'] == 2 ? '(下)' : '(全)')) : '';
        return $this->view->setVars([
            'id' => $id,
            'book' => $data,
            'checkHistory' => $checkHistory,
            'userId' => User::getId()
        ]);
    }
}